AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Sum Root to Leaf Numbers

The key idea

Each root-to-leaf path spells out a number. Carry the number built so far down the recursion: at each node compute cur = cur * 10 + node.val. When you reach a leaf, cur is that path's complete number — add it to the running total. Building the value top-down means you never have to store paths.

Problem

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 root-to-leaf path 1 -> 2 -> 3 represents the number 123.

Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer fits in a 32-bit integer.

A leaf node is a node with no children.

Constraints

Examples

Input: root = [1,2,3] Output: 25
Input: root = [4,9,0,5,1] Output: 1026

Complexity

Time: O(n) Space: O(h)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems