Sum Root to Leaf Numbers
Difficulty: Medium · Pattern: Trees & BST · LeetCode #129
Every node holds a digit 0–9, and each root-to-leaf path spells a number (path 1→2→3 is 123). Return the sum of all those numbers.
Examples
text
[1,2,3] → 12 + 13 = 25
[4,9,0,5,1] → 495 + 491 + 40 = 1026Hints
- Moving one level down appends a digit:
cur = cur * 10 + node.val.
Approach
Top-down DFS carrying cur. At a leaf, return cur. Otherwise return the sum of the two children's results. It's the same top-down state pattern as Good Nodes: each path's number is built incrementally, never stored as a string.
Complexity
Time: O(n). Space: O(h).
Python solution
def sumNumbers(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)JavaScript solution
function sumNumbers(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);
}