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
intarithmetic is enough.
- 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.
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
curis 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.
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.
Approach
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.
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.
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Ending a path at a null instead of at a leaf
if not node:
return curif not node:
return 0
...
if not node.left and not node.right:
return curA 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
total += cur # at every node
if not node.left and not node.right:
total += curInternal 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
self.cur = self.cur * 10 + node.val dfs(node.left) dfs(node.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.
Edge cases
[5]The root has no children, so it is a leaf and the answer is 5. It must not return 0.
[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.
Complexity
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.