2dbi

Sum Root to Leaf Numbers

viaLeetCode

Problem Each tree node holds a digit 0–9; every root-to-leaf path spells a number. Return the sum of all such numbers.

Input / Output

  • Input: tree root. Output: total sum.

Constraints

  • Up to 1000 nodes, depth <= 10 (sums fit in int); O(n) required.

Example

  • [1,2,3] → 12 + 13 = 25; [4,9,0,5,1] → 495 + 491 + 40 = 1026.

Expected approach

  • Preorder DFS carrying the running value: cur = cur*10 + node.val; at a leaf, add cur to the total. O(n)/O(h). The *10 accumulation (rather than string building) and correct leaf detection (both children null — a node with one child is NOT a leaf) are the graded details. Iterative stack of (node, value) pairs for the recursion-averse; overflow discussion if depth were unbounded.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account