Given the root of a binary tree, return the sum of all left leaves.

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Input & Output

Example 1 — Standard Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: 24
💡 Note: Left leaves are 9 (left child of 3) and 15 (left child of 20). Sum = 9 + 15 = 24
Example 2 — Single Node
$ Input: root = [1]
Output: 0
💡 Note: Root node has no parent, so it's not a left leaf. No left leaves exist.
Example 3 — Only Right Children
$ Input: root = [1,null,2,null,3]
Output: 0
💡 Note: All children are right children (2 is right child of 1, 3 is right child of 2). No left leaves.

Constraints

  • The number of nodes in the tree is in the range [1, 1000]
  • -1000 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Sum of Left Leaves - Optimized DFS INPUT Binary Tree Structure 3 9 LEFT LEAF 20 15 LEFT LEAF 7 right leaf Input Array: [3, 9, 20, null, null, 15, 7] ALGORITHM STEPS 1 Start DFS at Root Begin traversal from node 3 2 Check Left Children If left child is leaf, add value 3 Recurse Both Subtrees Process left and right children 4 Sum All Left Leaves Return accumulated sum DFS Traversal Trace: Visit 3: check left(9) 9 is leaf --> sum += 9 Visit 20: check left(15) 15 is leaf --> sum += 15 Visit 7: no children Total: 9 + 15 = 24 FINAL RESULT Left Leaves Identified 3 9 20 15 7 Calculation: 9 + 15 = 24 OUTPUT 24 OK - Sum verified Key Insight: A left leaf must satisfy TWO conditions: (1) it has no children (making it a leaf), and (2) it is the LEFT child of its parent. We track this by passing information from parent to child during DFS traversal. TutorialsPoint - Sum of Left Leaves | Optimized DFS Approach = Left Leaf = Other Node
Asked in
Facebook 15 Amazon 12 Google 8
180.0K Views
Medium Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen