logo CodeStepByStep logo

depthSum

Language/Type: Java binary trees

Write a method named depthSum that returns the sum of the values stored in a binary tree of integers weighted by the depth of each value. Your method accepts as its parameter a reference to a TreeNode representing the root of the tree. You should return the value at the root, plus 2 times the values stored at the next level of the tree, plus 3 times the values stored at the next level of the tree, plus 4 times the values stored at the next level of the tree, and so on. For example, in the tree below:

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

The sum would be computed as:

1 * 9 + 2 * (7 + 6) + 3 * (3 + 2 + 4) + 4 * (5 + 2) = 90

Assume that you are interacting with TreeNodes as defined below:

public class TreeNode {
    public int data;
    public TreeNode left;
    public TreeNode right;
    
    public TreeNode() { ... }
    public TreeNode(int data) { ... }
    public TreeNode(int data, TreeNode left, 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.