力扣-404-统计左子节点的和

题目:
404. Sum of Left Leaves(easy)
Find the sum of all left leaves in a given binary tree.
Example:

1
2
3
4
5
6
7
    3
/ \
9 20
/ \
15 7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

题目大意:
求出给定二叉树的所有左叶子之和。

解题思路:
递归 + 判断左叶子.
代码更易理解。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
Java:
public int sumOfLeftLeaves(TreeNode root){
if(root == null) return 0;
if(isLeaf(root.left)) return root.left.val + sumOfLeftLeaves(root.right);

return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
//一直往最底下找,相当于一直往内层嵌入,然后递归回来时从最底层网上加
}

private boolean isLeaf(TreeNode node){
if(node == null) return false;
return node.left == null && node.right == null;
}