Problem Statement

Sum Root to Leaf Numbers

You are given a binary tree. A binary tree is a structure where every spot, called a node, holds a value and can point to a left child and a right child below it. The top node is called the root, and a leaf is a node with no children at all (the bottom of a path). In this problem every node holds a single digit from 0 to 9. If you start at the root and walk straight down to any leaf, the digits you pass spell out a number. For example, walking 1 then 2 then 3 spells 123. We want to find every root-to-leaf number like this and add them all together. The natural way to walk a tree top to bottom is DFS, short for depth-first search, which means you go all the way down one path before backing up to try another. As we walk, we carry the number we have built so far. Each step down, we multiply that number by 10 (to shift the digits left) and add the new node's digit.

mediumTreeDFSTreesTime: O(n) · Space: O(h)

Signals to notice

sum all root-to-leaf paths as numbersdigits accumulate along pathDFS with running value

Brute force first

Enumerate all paths, convert each to a number, sum — same complexity but less elegant. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

DFS passing the accumulated number so far. At each node: currentNum = parentNum × 10 + node.val. At leaves, add currentNum to the total. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on root=[4,9,0,5,1] (4 → {9 → {5,1}, 0})

dfs(4, 0): num = 0*10+4 = 4; not leaf → recurse into 9 then 0
dfs(9, 4): num = 4*10+9 = 49; not leaf → recurse into 5 then 1
dfs(5, 49): num = 49*10+5 = 495; leaf → return 495
dfs(1, 49): num = 49*10+1 = 491; leaf → return 491; node 9 = 495+491 = 986
dfs(0, 4): num = 4*10+0 = 40; leaf → return 40
root 4 = 986 + 40 = 1026
return 1026

What must stay true

The number represented by a root-to-leaf path builds digit by digit: each level multiplies by 10 and adds the current digit. At leaves, the number is complete. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

function dfs(node, num):
    num = num * 10 + node.val
    if node is a leaf: return num
    return dfs(node.left, num) + dfs(node.right, num)
answer = dfs(root, 0)

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Multiplying at the wrong level — multiply BEFORE adding the current digit: newNum = oldNum × 10 + val. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Trees Pattern