mediumTreeDFSTrees

Sum Root to Leaf Numbers

mediumTime: 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.

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.

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