Sum of Left Leaves
You're given the root of a binary tree. A leaf is any node without children. A node counts as a left leaf only if it's a leaf and it's the left child of its parent. Add up the values of every left leaf in the tree and return the total — 0 if there aren't any.
Right leaves don't count, and neither does a node whose only child is on the right.
Input Format
Implement sumOfLeftLeaves(root). Inputs below show JavaScript function arguments; there is no stdin parsing.
Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 · Run Sample
Input
root = [3,9,20,null,null,15,7] Output
24 Example 2
Input
root = [1] Output
0 Constraints
- 1 <= number of nodes <= 1000
- -1000 <= Node.val <= 1000
Test Cases (2)
Case 1
Args: [[3,9,20,null,null,15,7]]
Expected: 24
Case 2
Args: [[1]]
Expected: 0
Topics
DFS
function sumOfLeftLeaves(root) {
if (!root) return 0;
let sum = 0;
if (root.left && !root.left.left && !root.left.right) sum += root.left.val;
else sum += sumOfLeftLeaves(root.left);
sum += sumOfLeftLeaves(root.right);
return sum;
}Time: O(n) | Space: O(h)
Saved in this browser only. Private to you.