leetcode1302. 层数最深叶子节点的和(深度优先搜索)
生活随笔
收集整理的這篇文章主要介紹了
leetcode1302. 层数最深叶子节点的和(深度优先搜索)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給你一棵二叉樹,請你返回層數(shù)最深的葉子節(jié)點(diǎn)的和。
代碼
class Solution {int[] depth=new int[]{Integer.MIN_VALUE,0};//記錄最深層數(shù)和對應(yīng)的和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])//和當(dāng)前最深層數(shù)一樣depth[1]+=root.val;return;}deep(root.left,cur+1);deep(root.right, cur+1);} }總結(jié)
以上是生活随笔為你收集整理的leetcode1302. 层数最深叶子节点的和(深度优先搜索)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到办丧事是什么意思
- 下一篇: leetcode面试题 04.02. 最