题目
题目链接 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;
}
}