leetcode1302. 层数最深叶子节点的和(深度优先搜索)

153 阅读1分钟

给你一棵二叉树,请你返回层数最深的叶子节点的和。

代码


class Solution {
    int[] depth=new int[]{Integer.MIN_VALUE,0};//记录最深层数和对应的和
    public int deepestLeavesSum(TreeNode root) {
        if(root==null) return 0;
       deep(root,0);
       return depth[1];
    }
    public void deep(TreeNode root,int cur) {
              if(root==null) return ;
        if(root.left==null&&root.right==null)
        {
            if(cur>depth[0])//更深的层
            {
                depth[0]=cur;
                depth[1]=root.val;
            }else if(cur==depth[0])//和当前最深层数一样
                depth[1]+=root.val;
            return;
        }
        deep(root.left,cur+1);
        deep(root.right, cur+1);
 
    }
}