給你一棵二叉樹,請你返回層數最深的葉子節點的和。
代碼
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);}
}