404. Sum of Left Leaves
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
return dfs(root, false);
}
public int dfs(TreeNode root, boolean isLeft){
if (root.left == null && root.right == null && isLeft) return root.val;
else {
int lsum = 0, rsum = 0;
if (root.left != null) lsum = dfs(root.left, true);
if (root.right != null) rsum = dfs(root.right, false);
return lsum + rsum;
}
}
}Last updated