Sum Root to Leaf Numbers - Problem

You are given the root of a binary tree containing digits from 0 to 9 only.

Each root-to-leaf path in the tree represents a number. For example, the root-to-leaf path 1 → 2 → 3 represents the number 123.

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.

A leaf node is a node with no children.

Input & Output

Example 1 — Simple Binary Tree
$ Input: root = [1,2,3]
Output: 25
💡 Note: Root-to-leaf paths: 1→2 gives number 12, and 1→3 gives number 13. Sum: 12 + 13 = 25
Example 2 — Deeper Tree
$ Input: root = [4,9,0,5,1]
Output: 1026
💡 Note: Root-to-leaf paths: 4→9→5 gives 495, 4→9→1 gives 491, 4→0 gives 40. Sum: 495 + 491 + 40 = 1026
Example 3 — Single Node
$ Input: root = [5]
Output: 5
💡 Note: Only one node, so the single root-to-leaf path is just 5

Constraints

  • The number of nodes in the tree is in the range [1, 1000]
  • 0 ≤ Node.val ≤ 9
  • The depth of the tree will not exceed 10

Visualization

Tap to expand
Sum Root to Leaf Numbers INPUT Binary Tree: root = [1,2,3] 1 2 3 (leaf) (leaf) Root-to-Leaf Paths: 1 --> 2 1 --> 3 root = [1, 2, 3] Digits 0-9 only ALGORITHM STEPS 1 Start DFS Begin at root, num = 0 2 Build Number num = num * 10 + node.val 3 Check Leaf If leaf: return num 4 Recurse & Sum Return left + right DFS Trace: dfs(1): num=0*10+1=1 dfs(2): num=1*10+2=12 dfs(3): num=1*10+3=13 Total = 12 + 13 = 25 FINAL RESULT 1 2 3 12 13 + 25 Output: 25 OK - Correct! Key Insight: DFS traversal builds numbers by multiplying the current value by 10 and adding the new digit. At each leaf node, return the accumulated number. Sum all paths: dfs(left) + dfs(right). Time: O(n) - visit each node once. Space: O(h) - recursion stack where h is tree height. TutorialsPoint - Sum Root to Leaf Numbers | DFS - Build Numbers During Traversal
Asked in
Amazon 45 Google 38 Microsoft 32 Apple 28
182.0K Views
Medium Frequency
~15 min Avg. Time
2.8K 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