Sum Root to Leaf Numbers solution explained
To solve Sum Root to Leaf Numbers, walk the tree depth first and carry the number built so far: at each node, multiply the carried value by 10 and add the node's digit, and when you reach a leaf, add that value to the total. Every node is visited once, so it runs in O(n) time with O(h) extra space for the recursion or stack, where h is the tree's height.
By Evin JohnPublished 7 min read
The problem in plain words
You get the root of a binary tree. Every node stores a single digit. Starting at the root and following child links down to a leaf, you can read the digits in order as one decimal number. A leaf is a node with no children at all. Add up the numbers for every root-to-leaf path and return the total.
2
/ \
5 0
/ \ \
1 3 8
Paths: 2-5-1 = 251, 2-5-3 = 253, 2-0-8 = 208
Answer: 251 + 253 + 208 = 712Two details hide in that picture. The node holding 0 has one child, so it is not a leaf and 20 is never counted on its own. And a zero digit in the middle of a path still shifts the number, so 2-0-8 is 208, not 28. A tree that is a single node holding 6 returns 6. A root of 9 with only a left child of 4 returns 94, not 9 + 94.
What interviewers look for
This is a short tree problem, so the interviewer is mostly testing whether you pass information downward cleanly and whether your leaf check is right. Candidates who treat "no left child" as a leaf, or who add the value at every null pointer, count some paths twice or count partial paths. A clean answer states the leaf rule before writing code. Follow-ups tend to stay close to the original:
- Path sum. Return whether any root-to-leaf path adds up to a target. Same walk, the carried state is a running sum instead of a number.
- List every path. Return the paths themselves, which needs a path list with backtracking and makes the output O(n·h) in the worst case.
- Binary digits. Nodes hold 0 or 1 and each path is a binary number. Multiply by 2 instead of 10, or shift left by one bit.
- Very deep trees. Ask whether the numbers can overflow. With depth above about 18 digits a 64-bit integer overflows, and JavaScript numbers lose exactness past 2^53, so a BigInt or a modulus may be required.
First version: build each path as text
The most literal reading is to record the digits as you go down, and at each leaf turn the collected string into an integer. It is correct and easy to explain. The cost is the copying: each leaf's string has up to h characters, and building or converting it takes that long, so the total is O(n·h). On a skewed tree that approaches O(n²). It is a fine opening line, and it makes a good test oracle.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_paths_as_text(root):
if root is None:
return 0
numbers = []
def walk(node, digits):
digits += str(node.val)
if node.left is None and node.right is None:
numbers.append(int(digits))
return
if node.left:
walk(node.left, digits)
if node.right:
walk(node.right, digits)
walk(root, "")
return sum(numbers)The efficient version: carry the number down
Appending a digit to a decimal number is the same as multiplying it by ten and adding the digit. So instead of carrying a string, carry an integer. The root starts with 0 · 10 + its digit. Each child receives its parent's value, multiplies by ten and adds its own digit. When a node has no children, its value is a complete path number and goes into the answer. Missing children return 0, so they add nothing.
def sum_numbers(root):
def dfs(node, so_far):
if node is None:
return 0
so_far = so_far * 10 + node.val
if node.left is None and node.right is None:
return so_far
return dfs(node.left, so_far) + dfs(node.right, so_far)
return dfs(root, 0)The JavaScript version below uses an explicit stack of (node, prefix) pairs, which avoids recursion entirely. That matters on a tree shaped like a long chain, where Python's default recursion limit of about a thousand frames and JavaScript's call stack can both run out.
function sumNumbers(root) {
if (root === null) return 0;
let total = 0;
const stack = [[root, 0]];
while (stack.length > 0) {
const [node, prefix] = stack.pop();
const value = prefix * 10 + node.val;
if (node.left === null && node.right === null) {
total += value;
continue;
}
if (node.right !== null) stack.push([node.right, value]);
if (node.left !== null) stack.push([node.left, value]);
}
return total;
}Trace the example: the root gives 2. Going left, 5 gives 25; its children give 251 and 253, both leaves. Going right, 0 gives 20, which has a child, so nothing is added yet; 8 gives 208, a leaf. Total 251 + 253 + 208 = 712.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Strings per path, convert at leaves | O(n·h) | O(h) per path string plus O(h) stack |
| Carry prefix · 10 + digit (recursive) | O(n) | O(h) call stack |
| Carry the prefix with an explicit stack | O(n) | O(h) for a DFS stack (O(w) if you use a queue instead) |
| Morris traversal (threaded tree) | O(n) | O(1), but it temporarily rewires the tree and is hard to get right live |
Edge cases to test
- An empty tree: return 0 rather than crash.
- One node: the answer is that digit.
- A node with exactly one child: it is not a leaf, so its partial number is not counted.
- Zero digits on the path, including a root of 0 (a path 0-4 reads as 4).
- A long one-sided chain: correct numbers, but watch the recursion depth and integer size.
- A complete tree where every path is the same length, a good check that every leaf is counted once.
Common mistakes
- Returning the running value at a null child. A node with one child then adds its partial number once for the missing side.
- Adding at every node instead of only at leaves.
- Keeping one shared variable for the current number and forgetting to undo it after the left subtree, so the right subtree starts from the wrong prefix. Passing the value as an argument avoids that.
- Concatenating strings and summing them as strings, which joins them instead of adding.
- Not asking about number size when the tree may be deep.
How to explain it out loud
Fictional example
- Candidate
- Every path is a number, and appending a digit means times ten plus the digit, so I will pass that running value down the tree.
- Candidate
- I only add it at a leaf, meaning both children are missing. A node with one child keeps going down the side it has.
- Candidate
- Each node is visited once, so O(n) time, and the stack is as deep as the tree. If the tree could be a thousand levels deep I would switch to the iterative stack.
- Interviewer
- What if the digits were bits?
- Candidate
- Then I multiply by two instead of ten. The rest stays the same.
Related walkthroughs
All Nodes Distance K in a Binary Tree also passes information along tree edges, but it has to travel upward too. Vertical Order Traversal carries a row and column instead of a number. Binary Tree Level Order Traversal shows the breadth-first alternative to this depth-first walk, and Delete Node in a BST is the next step up in tree editing.
Where Natively fits
When you rehearse tree problems on a Mac or Windows PC, Natively can read the problem from a screenshot and give you a nudge, such as which value to pass to the children, without writing the whole solution. It transcribes your practice session as well, so afterward you can check whether you stated the leaf rule before you started coding. See the AI interview assistant for how it works.
Questions people ask
How do you solve Sum Root to Leaf Numbers?
Do a depth-first walk that passes the number built so far. Each node turns the incoming value into value times 10 plus its digit, and a leaf adds that value to the total.
What counts as a leaf in Sum Root to Leaf Numbers?
Only a node with no children. A node with a single child is part of a longer path, so its partial number is never added on its own.
What is the time complexity of Sum Root to Leaf Numbers?
O(n) time because each node is visited once, and O(h) extra space for the recursion or explicit stack, where h is the tree height.
Can the path numbers overflow?
Yes, on deep trees. A path of more than about 18 digits overflows a 64-bit integer and JavaScript numbers stop being exact past 2 to the 53rd, so ask about the depth.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
