Find the sum of all left leaves in a given binary tree.

1
2
3
4
5
6
7
8
9
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

碰到树的问题,一般用递归做起来最方便。
这道题主要是如何判断一个节点是不是left leaf, 所以我声明了一个helper函数,把parent传进去了。
然后给根节点弄了个dummy的parent。因为根节点不是left leaf。所有dummy.right = root.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int sumOfLeftLeaves(TreeNode root) {
TreeNode dummy = new TreeNode(0);
dummy.right = root;
return helper(root, dummy);
}
public int helper(TreeNode node, TreeNode parent) {
if (node == null)
return 0;
if (node.left == null && node.right == null && node == parent.left)
return node.val;
int left = helper(node.left, node);
int right = helper(node.right, node);
return left + right;
}