Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
- 其实就是一个先序遍历,看看以各个节点为根节点的时候有没有左子叶注意是有没有左子叶,不是有没有左子树
- 左子叶判断方法,判断root的left是不是为空,然后看是不是叶子节点
class Solution {
int sum=0;
public int sumOfLeftLeaves(TreeNode root) {
if(root==null){
return sum;
}
if(root.left!=null){//是某棵树的左子树
if(root.left.left==null&&root.left.right==null){//进一步 是叶子,就可以返回了;
sum+=root.left.val;
}
//else{root=root.lef,这个做法是迭代给其他节点,
//刚开始竟然想迭代+递归,这样肯定会重复,直接看看根节点有没有左叶子,再递归看左右子树有没有左叶子
}
sumOfLeftLeaves(root.left);
sumOfLeftLeaves(root.right);
return sum;
}
}