InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Sum Root to Leaf Numbers

medium Original ↗ 00:00

Problem

You are given the root of a binary tree in which every node holds a single digit (09). Each root-to-leaf path spells out a number: reading the digits from the root down to the leaf gives a decimal integer (e.g. the path 1 → 2 → 3 represents 123).

Return the sum of all the numbers spelled by every root-to-leaf path.

A leaf is a node with no children. The tree is guaranteed to have at least one node, and the total fits in a 32-bit signed integer.

Examples

Example 1

Input: root = [1,2,3]
Output: 25

Paths: 1 → 2 = 12, and 1 → 3 = 13. Sum = 12 + 13 = 25.

Example 2

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

Paths: 4 → 9 → 5 = 495, 4 → 9 → 1 = 491, 4 → 0 = 40. Sum = 495 + 491 + 40 = 1026.

Example 3

Input: root = [7]
Output: 7

A single node is itself a leaf; the only path spells 7.

Constraints

  • The number of nodes is in the range [1, 1000].
  • 0 <= Node.val <= 9
  • The tree depth is at most 10, so each number has at most 10 digits and the sum fits in a 32-bit integer.

Think about it first

Hint 1 As you walk down from the root, how does the number-so-far change when you step to a child? If the number built to a node is `cur`, stepping to a child with digit `d` gives `cur * 10 + d`.
Hint 2 Pass the running number down the tree as a parameter. You only "finish" a number when you reach a leaf — that is when you add it to the total.
Hint 3 DFS with signature `dfs(node, cur)`: if `node` is a leaf, return `cur * 10 + node.val`. Otherwise return the sum of `dfs` over its non-null children, each called with `cur * 10 + node.val`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug