LeetCode 404 sum of left leaves
Find the sum of all left leaves in a given binary tree
think about this, when we reached leaf, how are we gonna to know if it is left leaf or not?
of course we can modify the iterate version of preorder traverse, it’s very simple.
but how are we gonna do it recursively?
class Solution {
private int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
return sumOfLeftLeaves(root, false);
}
private int sumOfLeftLeaves(TreeNode root, boolean isLeft) {
if (root == null) return 0;
if (root.left == null && root.right == null && isLeft) {
return root.val;
}
return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false);
}
}
so the function of recursion will be:
sumOfLeftLeaves(root) = sumOfLeftLeaves(root, false) = sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false) //and the ending is when root is null or we reached the leaf node which is left, it’s over.

浙公网安备 33010602011771号