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 TreeNode
s 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) { ... }
}