logo CodeStepByStep logo

tiltSum

Language/Type: Java binary trees
Related Links:

Write a method named tiltSum that returns the sum of the "tilt" of every node in a binary tree of integers. Your method accepts as its parameter a TreeNode that refers to the root of the tree and returns the tree's new root. The "tilt" of a tree node is defined as the absolute difference between the sums of all values in that node's two subtrees.

For example, suppose a variable called root refers to the root of the following tree:

(4 (2 (3) (5)) (9 / (7)))

The tilts of nodes 3, 5, and 7 are 0. The tilt of node 2 is |3-5| or 2. The tilt of node 9 is |7-0| or 7. The tilt of node 4 (the root) is |(2+3+5) - (9+7)| or 6. The overall tilt sum is 0+0+0+2+7+6, so the call of tiltSum(root) should return 15.

Assume that you are interacting with TreeNodes as defined below:

public class TreeNode {
    public int data;
    public TreeNode left;
    public TreeNode right;
    ...
}
Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.