A basic Java sample: Given a binary tree and an integer which is the depth of the target level. And calculate the sum of the nodes in the target level.
I am adding the value in the functions to the left and right node. Why this solution doesn't work in this case, Can anyone help explain?
Also, when the travese
function got returned, is it returning to the parent root or more like break;
in for loop and the flow got stopped?
private int sum;
public int levelSum(TreeNode root, int level) {
sum = 0;
traverse(root, 1, level, 0);
return sum;
}
public void traverse(TreeNode root, int depth, int level, int sum) {
if(root == null) {
return;
}
if(depth == level) {
return;
}
if(root.left != null) {
traverse(root.left, depth + 1, level, sum + root.left.val);
}
if(root.right != null) {
traverse(root.right, depth + 1, level, sum + root.right.val);
}
}
sum
in thelevelSum
routine. Andtraverse
returnsvoid
, so you have no way to pass the intermediatesum
values back up the call stack. You should probably merge these two routines into a single function that returnsint
. – Jim Lewisfor
loop in your posted code, so I cannot answer your last question. – MikeCAT