一、題目內容

二、題目分析
很簡單的題目,通過dfs獲取樹的高度,然后再判斷當前葉子節點高度是否等于樹的高度,是就讓結果值加上葉子節點的值,否則就遍歷左右子樹,
三、代碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
static int ans=0;
public int deepestLeavesSum(TreeNode root) {
int h=height(root);
System.out.print(h);
dfs(root,1,h);
return ans;
}
public int height(TreeNode root)
{
if(root.left!=null&&root.right==null)
return height(root.left)+1;
else if(root.left==null&&root.right!=null)
return height(root.right)+1;
else if(root.left!=null&&root.right!=null)
return Math.max(height(root.left)+1,height(root.right)+1);
else return 1;
}
public void dfs(TreeNode root,int nowh,int h){
if(nowh==h){
ans+=root.val;
return;
}
if(root.left!=null)
dfs(root.left,nowh+1,h);
if(root.right!=null)
dfs(root.right,nowh+1,h);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/333604.html
標籤:其他
上一篇:104. 二叉樹的最大深度
