mediumTreeDFSTrees

Sum Root to Leaf Numbers

mediumTime: O(n)Space: O(h)

Recognize the pattern

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

Brute force idea

The naive version of Sum Root to Leaf Numbers sounds like this: 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.

Better approach

The deeper shift in Sum Root to Leaf Numbers is this: 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.

Key invariant

At the center of Sum Root to Leaf Numbers is one steady idea: 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.

Watch out for

The trap in Sum Root to Leaf Numbers usually looks like this: 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