Skip to content
Decoder

Sum Root to Leaf Numbers

Medium

Problem

Every node of a binary tree holds a single digit from 0 to 9. Reading the digits along a path from the root down to a leaf spells a number: the path 6 → 1 → 7 spells 617. A leaf is a node with no children. Return the sum of the numbers spelled by every root-to-leaf path.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
[6, 1, 4, null, 7]
Output
681
Why
617 + 64

Example 2

Input
[3, 5, 0, 9]
Output
389
Why
359 + 30

Example 3

Input
[5]
Output
5

Constraints

  • 1 <= number of nodes <= 1000
  • 0 <= Node.val <= 9
  • The tree is at most 10 levels deep, and the answer fits in a 32-bit integer.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.