Sum of Left Leaves
Easy · tree dfs
You are given the root of a binary tree. A leaf is a node with no children. A left leaf is a leaf that sits in the left slot of its parent.
Return the sum of the values of all left leaves. A leaf in the right slot of its parent does not count, and neither does the root on its own, because the root has no parent. If the tree is empty or has no left leaf, return 0.
Examples
Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: 24
Node 9 is a left leaf and node 15 is the left leaf under 20. Node 7 is a right leaf, so it is skipped: 9 + 15 = 24.
Example 2
Input: root = [1]
Output: 0
The only node is the root, which has no parent.
Example 3
Input: root = [1, 2, 3, 4, 5]
Output: 4
Node 2 has children so it is not a leaf, and node 3 is a right leaf. Only node 4 counts.
Constraints
- The number of nodes is in the range [0, 1000].
- -1000 <= Node.val <= 1000