Sum Root to Leaf Numbers (LeetCode 129): Solution and Explanation
Every node of a binary tree holds a digit from 0 to 9, and every root-to-leaf path spells a number read from the root down. Return the sum of all those numbers. The tree has up to 1000 nodes and is at most 10 levels deep, so the answer fits in a 32-bit integer.
Intuition
Writing a digit after a number multiplies the number by 10 and adds the digit: 12 followed by 3 is 12 * 10 + 3 = 123. Walking from a node to its child does exactly that, so the number for any node is its parent's number times 10 plus its own digit.
That means a depth-first walk only has to carry one integer, the number spelled so far. Each child gets its own copy, so the left and right branches never interfere.
A number is complete only at a leaf. Internal nodes are prefixes of longer numbers and must not be counted on their own, so the walk adds cur to the answer only when both children are missing.
Approach: DFS carrying the number so far
- Define dfs(node, cur) returning the sum of every number that ends in node's subtree.
- If node is null, return 0.
- Update cur = cur * 10 + node.val.
- If node has no children, return cur.
- Otherwise return dfs(node.left, cur) + dfs(node.right, cur).
- The answer is dfs(root, 0).
Step-by-step example
root = [4,9,0,5,1]
- dfs(4, 0): cur = 0 * 10 + 4 = 4. Node 4 has children, so recurse left then right.
- dfs(9, 4): cur = 49. Node 9 has two children.
- dfs(5, 49): cur = 495 and 5 is a leaf, so return 495.
- dfs(1, 49): cur = 491 and 1 is a leaf, so return 491. Node 9 returns 495 + 491 = 986.
- dfs(0, 4): cur = 40 and 0 is a leaf, so return 40.
- Node 4 returns 986 + 40 = 1026, which is the answer.
Code: Python, Java, C++
1class Solution:
2 def sumNumbers(self, root: Optional[TreeNode]) -> int:
3 def dfs(node: Optional[TreeNode], cur: int) -> int:
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)1class Solution {
2 public int sumNumbers(TreeNode root) {
3 return dfs(root, 0);
4 }
5
6 private int dfs(TreeNode node, int cur) {
7 if (node == null) return 0;
8 cur = cur * 10 + node.val;
9 if (node.left == null && node.right == null) return cur;
10 return dfs(node.left, cur) + dfs(node.right, cur);
11 }
12}1class Solution {
2public:
3 int sumNumbers(TreeNode* root) {
4 return dfs(root, 0);
5 }
6
7private:
8 int dfs(TreeNode* node, int cur) {
9 if (!node) return 0;
10 cur = cur * 10 + node->val;
11 if (!node->left && !node->right) return cur;
12 return dfs(node->left, cur) + dfs(node->right, cur);
13 }
14};Time and space complexity
O(n)
Each node is visited once and does constant work.
O(h)
The recursion stack holds one frame per level of the current path, and the height h is at most 10 here.
Other approaches
Iterative DFS with a stack of (node, cur) pairs (time O(n), space O(h))
Push (root, root.val). Pop a pair, add cur to the total if the node is a leaf, otherwise push each child with cur * 10 + child.val. Same O(n) time, and it avoids recursion entirely.
BFS with a queue of (node, cur) pairs (time O(n), space O(w))
The same idea level by level. It works because each pair carries its own number, but the queue can hold a whole level, which is O(n) for a wide tree.
Morris traversal (time O(n), space O(1))
Threads the tree to walk it with O(1) extra space, dividing cur by 10 when climbing back along a thread. Correct but fiddly, and rarely worth it for a tree only 10 levels deep.
Common mistakes
- Adding cur at every node instead of only at leaves. A node with one child is still not a leaf, and counting it adds a prefix that is not a full number.
- Treating a node with one missing child as a leaf. The path has to continue down the child that exists.
- Building the number as a string and parsing it at each leaf. It works, but it costs O(h) per leaf for no benefit.
- Forgetting that 0 is a valid digit. A leading 0 at the root simply drops out of the number, which cur * 10 + val already handles.
Frequently asked questions
Why does a null child return 0 rather than cur?
A null child is not the end of a path. If it returned cur, a node with only one child would count its own prefix as an extra number. Returning 0 makes a missing side add nothing, and the leaf check catches the real ends.
Can the numbers overflow?
The tree is at most 10 levels deep, so each number has at most 10 digits, and the problem guarantees the total fits in a 32-bit integer. In languages with fixed-width ints you can use a 64-bit accumulator if you want extra margin.
Does the order of visiting children matter?
No. Addition is commutative, so left-first or right-first gives the same total.