Sum Root to Leaf Numbers
Medium
Topics
Each root-to-leaf path in a binary tree represents a number formed by concatenating the node digits (each node value is a single digit 0-9). Return the total sum of all root-to-leaf numbers.
Example 1
acc * 10 + node.val into the recursion builds it on the way down, so no path ever has to be stored. The 2 path(s) total 25.null marks a missing child.Input: root = [1,2,3] Output: 25 Explanation: Paths 12 and 13; 12 + 13 = 25.
Example 2
Input: root = [4,9,0,5,1] Output: 1026
Constraints
- 1 <= number of nodes <= 1000
- 0 <= Node.val <= 9
Editorial — intuition, approach, complexity and pitfalls
Intuition
Each root-to-leaf path spells a number, and the digits arrive in the order you need them. Carry the number built so far and extend it with cur * 10 + node.val on the way down; at a leaf, that value is the path's number.
This is the pattern worth naming: accumulate on descent rather than collecting the path and converting afterwards. No list of digits, no string building, no second pass — and it generalises to any base or any left-to-right fold over a path.
Approach
- Recurse with the number accumulated so far, starting at 0.
- Extend it:
cur = cur * 10 + node.val. - At a leaf, return
cur. - Otherwise return the sum of both children's results.
Dry Run
4
/ \
9 0
/ \
5 1
path 4 -> 9 -> 5 4, then 49, then 495
path 4 -> 9 -> 1 4, then 49, then 491
path 4 -> 0 4, then 40
total 495 + 491 + 40 = 1026
single node 0 -> 0
0 with one child 1 -> 1 the leading zero does not create a two-digit numberComplexity
- Time — O(n): one visit per node.
- Space — O(h) for the call stack, which is O(log n) on a balanced tree and O(n) on a path. At the stated bound of 1,000 nodes a degenerate path sits right at Python's default recursion limit, which is why the harness on this page raises it.
Common Pitfalls
- Returning
curat a null child rather than at a leaf. A node with one child then contributes its own prefix as if it were a complete path, double-counting every single-child node. - Building the number as a string and parsing it at the leaf. Correct, but it allocates per node and the arithmetic form is both simpler and faster.
- Collecting all paths into a list first and summing afterwards. That is O(n·h) space for information you consume immediately.
- Using a single mutable accumulator shared across the recursion without undoing it on the way out. Passing
curby value sidesteps the problem entirely — which is the reason to pass it rather than mutate it. - Worrying about overflow. The tree holds at most 1,000 nodes but a path of 1,000 digits would be an astronomically large number — in a fixed-width language this overflows long before that, so it is worth asking the interviewer how deep the tree can be before claiming the arithmetic is safe. For the stated inputs it is fine; the reasoning is the point.
- Treating a node whose value is 0 as absent. Zero is a legal digit.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sumNumbers(self, root):
def dfs(node, cur):
if not node: return 0
cur = cur * 10 + node.val
if not node.left and not node.right: return cur
return dfs(node.left, cur) + dfs(node.right, cur)
return dfs(root, 0)import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int sumNumbers(TreeNode root) {
return dfs(root, 0);
}
private int dfs(TreeNode node, int cur) {
if (node == null) return 0;
cur = cur * 10 + node.val;
if (node.left == null && node.right == null) return cur;
return dfs(node.left, cur) + dfs(node.right, cur);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int sumNumbers(TreeNode* root) {
function<int(TreeNode*,int)> dfs = [&](TreeNode* node, int cur) -> int {
if (!node) return 0;
cur = cur * 10 + node->val;
if (!node->left && !node->right) return cur;
return dfs(node->left, cur) + dfs(node->right, cur);
};
return dfs(root, 0);
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var sumNumbers = function(root) {
const dfs = (node, cur) => {
if (!node) return 0;
cur = cur * 10 + node.val;
if (!node.left && !node.right) return cur;
return dfs(node.left, cur) + dfs(node.right, cur);
};
return dfs(root, 0);
};