404. Sum of Left Leaves
Leetcode TreeFind 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.
分析¶
如果是求所有叶子结点的和会比较简单,为了区分左叶子结点和右叶子节点,特别的,在参数列表上增加了isLeft
参数。
private static int sum;
public int sumOfLeftLeaves(TreeNode root) {
sum = 0;
sumOfLeftLeavesHelper(root, false);
return sum;
}
private void sumOfLeftLeavesHelper(TreeNode root, boolean isLeft){
if (root == null) return;
if (root.left == null && root.right == null && isLeft) sum += root.val;
sumOfLeftLeavesHelper(root.left, true);
sumOfLeftLeavesHelper(root.right, false);
}