AlgoInsight

DSA problem

Sum Root to Leaf Numbers

MediumTree Traversal - Post-OrderPattern: Tree Traversal - Post-Ordertop600AmazonMicrosoftBloombergGoogleApple

You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number — for example, the path 1 → 2 → 3 represents the number 123. Return the total sum of all root-to-leaf numbers.

A leaf is a node with no children. The test cases are guaranteed so that the total sum fits within a 32-bit signed integer, so you do not need to worry about overflow.

The natural approach carries a running number down the tree. At every node we update cur = cur * 10 + node.val, which is the standard "shift left in base 10 and append a digit" trick. When we reach a leaf, the running number is exactly the value formed by the path from the root, so we add it to the running total.

The traversal can be coded as a DFS that takes the running number as a parameter, or as a post-order recursion that returns the partial sum from each subtree given the running prefix. Either form visits every node once, performs constant arithmetic per node, and uses O(h) stack space for the recursion. Total complexity: O(n) time and O(h) space.

Examples

Example 1
Input: root = [1,2,3]
Output: 25
Explanation: Path 1→2 forms 12 and path 1→3 forms 13; the total is 12 + 13 = 25.
Example 2
Input: root = [4,9,0,5,1]
Output: 1026
Explanation: Paths form 495, 491, and 40; their sum is 495 + 491 + 40 = 1026.
Example 3
Input: root = [1]
Output: 1
Explanation: A single node is both root and leaf, so the only path forms the number 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

treebinary-treedepth-first-searchrecursion

Browse all DSA problems