lint0482. Binary Tree Level Sum

    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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容