CodingNodes / Trees / Sum Root to Leaf Numbers System design Space play · ←→ step · R restart

Problem

Each node of a binary tree holds one digit, 0 to 9. Reading the digits along a path from the root down to a leaf, in order, spells a number: the path 1 → 2 → 3 spells 123. A leaf is a node with no children.

Given the root, return the sum of the numbers spelled by all root-to-leaf paths. The tree is given in level order, with null for a missing child.

Constraints

  • 1 ≤ number of nodes ≤ 10
  • 0 ≤ Node.val ≤ 9
  • The depth is at most 4, so every path number fits in an int

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(h)

Time: Every node is visited once and does a fixed amount of arithmetic.

Space: The recursion is as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.

Walk down from the root and carry the number spelled so far. Stepping onto a node turns the carried number into cur * 10 + digit, which appends the digit. At a leaf the number is complete, so return it. At any other node, return the sum of its two subtrees. An empty child returns 0, so a node with one child is not mistaken for a leaf.