leetcode404. sum of left leaves

累加二叉树所有左叶子节点的值。

404. Sum of Left Leaves

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
public int sum = 0;
public int (TreeNode root) {
if (root != null) preorderWalk(root);
return sum;
}
public void preorderWalk(TreeNode root) {
if (root == null) return;
if (root.left != null) {
if (root.left.right == null && root.left.left == null) sum += root.left.val;
}
preorderWalk(root.left);
preorderWalk(root.right);
}