LeetCode #129 Medium

Sum Root to Leaf Numbers

Sum Root to Leaf Numbers is LeetCode 129 (Medium). Every node of a binary tree holds one digit from 0 to 9, and each path from the root down to a leaf spells a number, digit by digit.

  • Return the sum of all the numbers formed from root to leaf paths.
  • A leaf is a node with no children.
  • The tree is at most 10 levels deep and the answer fits in a 32-bit integer, so plain int arithmetic is enough.
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.
treedfsrecursion
Open on LeetCode ↗
02

Intuition

Reading a path from the top, each new digit pushes the number so far one place left and fills the ones place. In arithmetic that is cur * 10 + digit: 4 becomes 49, then 495.

So pass cur down the recursion as a plain number:

  • Going down: each node turns its parent's number into its own with one multiply and one add.
  • At a leaf: the path is complete, so cur is one of the numbers to add.
  • Coming back up: each call returns the total of the leaf numbers below it, so the root's call returns the answer.

Since cur is an integer argument, each branch gets its own copy and nothing is undone.

How to spot this pattern

When each root-to-leaf path builds a value digit by digit (or bit by bit), carry the partial value down as an argument and collect it at the leaves. The same shape solves the binary-digit version with cur * 2 in place of cur * 10.

03

Approach

Try it first

Before reading on, work out what number the path 4 → 9 → 5 spells, and how 49 turns into 495 without using strings. Then decide where in the recursion a finished number should be counted. Aim for one visit per node.

1

Pass the number so far into each call

Write dfs(node, cur), where cur is the number spelled by the path above node. The first call is dfs(root, 0), because nothing has been read before the root.

2

Return 0 for a missing child

If node is null, return 0. A node with only one child still calls the helper on its empty side, and no path ends there, so that side must add nothing to the total.

3

Extend the number at the node

Set cur = cur * 10 + node.val. Multiplying by 10 moves every digit read so far one place left, which frees the ones place for this node's digit.

4

Return the number at a leaf

If the node has no left and no right child, return cur. Only at a leaf is the path complete, so only there does a number count.

5

Add the results from both sides

Otherwise return dfs(node.left, cur) + dfs(node.right, cur). Every leaf lies below exactly one of the two children, so each path's number is counted exactly once on its way back to the root.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def sumNumbers(self, root):
▶3 def dfs(node, cur):
▶4 if not node:
▶5 return 0
▶6 cur = cur * 10 + node.val
▶7 if not node.left and not node.right:
▶8 return cur
▶9 return dfs(node.left, cur) + dfs(node.right, cur)
▶10 
▶11 return dfs(root, 0)
123this call returnsstill going downleaf numbersnone yetstart at the root with 0 read so far
cur0nothing read yet
Each path from the root to a leaf spells a number. The walk starts at the root with 0 as the number read so far, because no digit has been read yet.
1123this call returnsstill going downleaf numbersnone yetread 1 → number so far 1
cur10 shifted left, then + 1
The root's digit is the first digit, so the number so far is 1.
112123this call returnsstill going downleaf numbersnone yetread 2 → number so far 12
cur121 shifted left, then + 2
Multiplying 1 by 10 moves its digits one place left and frees the ones place for 2, giving 12: exactly the digits on the path from the root to here.
112123this call returns12leaf numbers122 is a leaf → 12 is a full number
returns12
leaf numbers1
Node 2 has no children, so the path ends here and 12 is one of the numbers to add. The call returns it to its parent.
11212313this call returnsstill going downleaf numbers12read 3 → number so far 13
cur131 shifted left, then + 3
Multiplying 1 by 10 moves its digits one place left and frees the ones place for 3, giving 13: exactly the digits on the path from the root to here.
11212313this call returns13leaf numbers12+133 is a leaf → 13 is a full number
returns13
leaf numbers2
Node 3 has no children, so the path ends here and 13 is one of the numbers to add. The call returns it to its parent.
11212313this call returns12+13=25leaf numbers12+13both sides of 1 done → returns 25
left side12
right side13
returns25
Every leaf below 1 sits under exactly one of its two children, so adding the two results counts each of those paths once: 25.
11212313this call returnsstill going downleaf numbers12+13=25answer: 25
result25
The root's call returns 25, the sum of the 2 leaf numbers in the bottom row. Each node did one multiply and one add, so the whole walk is linear in the number of nodes.
05

Common pitfalls

Ending a path at a null instead of at a leaf

✗ Wrong
if not node:
    return cur
✓ Right
if not node:
    return 0
...
if not node.left and not node.right:
    return cur

A leaf has two null children, so its number is returned twice, and a one-child node turns its empty side into a fake path. On [1,2] the only path spells 12, but this version returns 12 + 12 + 1 = 25.

Adding the number at every node

✗ Wrong
total += cur  # at every node
✓ Right
if not node.left and not node.right:
    total += cur

Internal nodes hold only the start of a number. On [1,2,3] the answer is 12 + 13 = 25, but adding at every node also counts the root's 1 and returns 26.

Keeping the number in one shared variable

✗ Wrong
self.cur = self.cur * 10 + node.val
dfs(node.left)
dfs(node.right)
✓ Right
dfs(node.left, cur)
dfs(node.right, cur)

The left subtree's digits are still in the shared value when the right subtree starts. On [1,2,3] the right path reads 123 instead of 13. Passing cur as an argument gives each branch its own copy.

06

Edge cases

A single node, [5]

The root has no children, so it is a leaf and the answer is 5. It must not return 0.

Zero digits, [0,1,0]

The paths spell 01 and 00, which are the numbers 1 and 0, so the answer is 1. The multiply-add drops a leading zero by itself.

07

Complexity

Time
O(n)
Space
O(h)
Each node does one multiply and one add. The recursion is as deep as the tree is tall, and that is at most 10 levels here.
08

Sum Root to Leaf Numbers FAQ

How is this different from Path Sum?

Path Sum adds the node values along a path and compares the total with a target. Here a value's position matters: the same digits 1, 2 spell 12 on one path and 21 on another.

What changes in Sum of Root To Leaf Binary Numbers?

That problem (LeetCode 1022) stores bits instead of digits, so each step is cur * 2 + bit, often written cur << 1 | bit. The leaf rule and the rest of the walk stay the same.

Can it be solved without recursion?

Yes. Keep a queue of (node, number so far) pairs, start with (root, root.val), and add the number whenever a leaf comes out of the queue. It costs O(n) extra space for the queue instead of the call stack.