Given the root of a binary tree, return the sum of all left leaves. A left leaf is a leaf node that is the left child of its parent.

Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves: 9 and 15. Their sum is 9 + 15 = 24.
Input: root = [1]
Output: 0
Explanation: The single node is the root (not a left leaf), so the sum is 0.
Constraints:

Contents

Recursive DFS

The challenge is distinguishing a left leaf from a right leaf. We solve this by passing a boolean flag isLeft to the recursive helper that indicates whether the current node was reached as a left child. When we find a leaf node with isLeft == true, we add its value to the sum.

Algorithm:
public int sumOfLeftLeaves(TreeNode root) { return dfs(root, false); } private int dfs(TreeNode node, boolean isLeft) { if (node == null) return 0; // leaf node that was reached as a left child if (node.left == null && node.right == null) { return isLeft ? node.val : 0; } return dfs(node.left, true) // left child → isLeft = true + dfs(node.right, false); // right child → isLeft = false }
Trace through Example 1: root = [3,9,20,null,null,15,7]
NodeisLeftIs Leaf?Contribution
3falseNorecurse
9trueYes+9
20falseNorecurse
15trueYes+15
7falseYes+0

Total = 9 + 15 = 24.