Skip to content

Sum Root to Leaf Numbers

MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.

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.

[6, 1, 4, null, 7]   →  681   (617 + 64)
[3, 5, 0, 9]         →  389   (359 + 30)
[5]                  →  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.