InterviewPrepKit

Home / Coding / Trees

Sum Root to Leaf Numbers

medium Original β†—
Solving tips
  • Thread the running number down as a DFS parameter; stepping to a child updates it as cur*10 + node.val, no string building needed.
  • Only finalize (add cur to the total) at a leaf (no left and no right child); adding at internal nodes double-counts prefixes.
  • A node with one child is NOT a leaf; recurse into the existing child and let the null branch return 0.
  • O(n) time visiting each node once, O(h) recursion space; pass cur by value so sibling branches don't leak digits.

Problem

You are given the root of a binary tree in which every node holds a single digit (0–9). 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`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.