題目
題目鏈接 https://leetcode-cn.com/problems/sum-of-left-leaves/
計算給定二叉樹的所有左葉子之和。
示例:
3
/ \
9 20
/ \
15 7
在這個二叉樹中,有兩個左葉子,分別是 9 和 15,所以返回 24
Related Topics
樹
代碼
我們都知道求所有的節點的和
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return solve(root);
}
public int solve(TreeNode root){
if(root==null){
return 0;
}
int left = solve(root.left);
int right = solve(root.right);
return root.val+left+right;
}
}
在基礎上改一改可以求所有葉子節點的和
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return solve(root);
}
public int solve(TreeNode root){
if(root==null){
return 0;
}
int sum=0;
// 葉子節點
if (root.left == null && root.right == null) {
sum = root.val;
}
int left = solve(root.left);
int right = solve(root.right);
return sum+left+right;
}
}
在改一改就可以求所有左節點的和了
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return solve(root,false);
}
public int solve(TreeNode root,boolean flag){
if(root==null){
return 0;
}
int sum=0;
// 葉子節點
if (flag&&root.left == null && root.right == null) {
sum = root.val;
}
int left = solve(root.left,true);
int right = solve(root.right,false);
return sum+left+right;
}
}