美文网首页
lint0482. Binary Tree Level Sum

lint0482. Binary Tree Level Sum

作者: 日光降临 | 来源:发表于2019-02-24 15:50 被阅读0次
    1. 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;
    }
}

相关文章

网友评论

      本文标题:lint0482. Binary Tree Level Sum

      本文链接:https://www.haomeiwen.com/subject/zycbyqtx.html