欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

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

发布时间:2023/11/29 40 豆豆
生活随笔 收集整理的这篇文章主要介绍了 leetcode1302. 层数最深叶子节点的和(深度优先搜索) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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

代码

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);} }

总结

以上是生活随笔为你收集整理的leetcode1302. 层数最深叶子节点的和(深度优先搜索)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。