Sum Root to Leaf Numbers
Appending a digit to a number shifts everything already there one place left: 49 followed by 5 is 49*10+5=495. So carry a running integer DOWN the recursion — multiply by 10 and add the node's digit at every step. A leaf hands that integer straight back up; an internal node just adds what its two children returned.
Details
Animated on: Each node holds a single digit. Return the sum of all numbers formed by concatenating digits along every root-to-leaf path, for the tree [4, 9, 0, 5, 1].
Problem:Sum Root to Leaf NumbersMedium
Binary Trees
step 1 / 11
Call stack
Enter node 4 with incoming total 0. New running total = 0 * 10 + 4 = 4. It has children, so recurse into both before it can return anything.
1FUNCTION dfs(node, cur):2 cur <- cur * 10 + node.val3 IF node is leaf:4 RETURN cur5 ELSE:6 RETURN dfs(node.left, cur) + dfs(node.right, cur)7END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 11 steps
- Enter node 4 with incoming total 0. New running total = 0 * 10 + 4 = 4. It has children, so recurse into both before it can return anything.
- Enter node 9 with incoming total 4. New running total = 4 * 10 + 9 = 49. It has children, so recurse into both before it can return anything.
- Node 5 is a leaf. Running total becomes 49 * 10 + 5 = 495 — that IS the number for this root-to-leaf path.
- dfs(5) returns 495 and pops off the stack.
- Node 1 is a leaf. Running total becomes 49 * 10 + 1 = 491 — that IS the number for this root-to-leaf path.
- dfs(1) returns 491 and pops off the stack.
- Both children of 9 are back: 495 + 491 = 986. dfs(9) returns 986.
- Node 0 is a leaf. Running total becomes 4 * 10 + 0 = 40 — that IS the number for this root-to-leaf path.
- dfs(0) returns 40 and pops off the stack.
- Both children of 4 are back: 986 + 40 = 1026. dfs(4) returns 1026.
- Answer = 1026: the three root-to-leaf numbers 495, 491 and 40 all summed exactly once, with no partial prefix counted.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.