AlgoInsight

DSA problem

Sum of Left Leaves

EasyTree Traversal - Pre OrderPattern: Tree Traversal - Pre Ordertop600AmazonMicrosoftBloombergAdobe

Given the root of a binary tree, return the sum of all left leaves — that is, leaf nodes that are themselves the left child of their parent. Right leaves and internal nodes are ignored.

A node qualifies for the sum iff it satisfies both conditions: it has no children (i.e. it is a leaf), and it is positioned as its parent's left child. Note that the root itself can never be counted: it has no parent and therefore cannot be a "left" leaf, even if both its children are null.

The most natural way to encode the position information is with an extra boolean parameter — is_left — passed down the recursion. When we recurse into a node's left child we pass True; when we recurse right we pass False. At each visit, if the current node is a leaf and is_left is True, we add its value to a running total.

This is a textbook preorder DFS: examine the current node first (apply the test), then recurse left and right. Time complexity is O(n) since every node is visited exactly once; space is O(h) for the recursion stack, where h is the height of the tree.

Examples

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: Node 9 is a leaf and the left child of 3 — count it. Node 15 is a leaf and the left child of 20 — count it. Node 7 is a leaf but the right child, so skipped. Sum = 9 + 15 = 24.
Example 2
Input: root = [1]
Output: 0
Explanation: The only node is the root itself, which has no parent and therefore is not a left leaf. The sum is 0.
Example 3
Input: root = [1,2,3,4,5]
Output: 4
Explanation: Node 4 is a leaf and a left child of 2 — count it. Node 5 is a leaf but a right child, so skipped. Sum = 4.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchrecursion

Browse all DSA problems