- Binary Tree Level Sum
Given a binary tree and an integer which is the depth of the target level.
Calculate the sum of the nodes in the target level.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
public int sum;
public void helper(TreeNode root, int level, int depth){
if(root==null)
return;
if(depth==level){
sum+=root.val;
return;
}
helper(root.left,level,depth+1);
helper(root.right,level,depth+1);
}
public int levelSum(TreeNode root, int level) {
sum = 0;
helper(root,level,1);
return sum;
}
}