oneby7

Binary Trees Depth first: return a value up

360. Sum Root to Leaf Numbers

Medium

You are given root, the root node of a binary tree. Every node holds a single digit, from 0 to 9. Each path from the root down to a leaf spells a number: its digits are the values on the path, with the root's digit first. Return the sum of the numbers that all the root-to-leaf paths spell.

A leaf is a node with no children. A node with one child is not a leaf, so no path ends there. A path that starts with 0 spells a number with fewer digits: 0 → 4 → 2 spells 42.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

146739

Input: root = [6, 1, 3, null, 4, 7, 9]

Output: 1890

Explanation: The tree has three leaves, so three paths: 6 → 1 → 4 spells 614, 6 → 3 → 7 spells 637, and 6 → 3 → 9 spells 639. 614 + 637 + 639 = 1890. The node 1 has a child, so 61 is not one of the numbers.

Example 2

5020

Input: root = [0, 5, 0, null, null, 2]

Output: 7

Explanation: The paths spell 05 and 002, which are the numbers 5 and 2. A leading 0 adds nothing to a number.

Example 3

200

Input: root = [2, null, 0, 0]

Output: 200

Explanation: Each node has one child, so there is one leaf and one path: 2 → 0 → 0. The zeros at the end are digits of the number, so it is 200.

Check your understanding

Work out the answer for this input before you write any code.

root = [1, 2, 3, 4, null, null, 5]

Constraints

  • 1 ≤ number of nodes ≤ 1023
  • 0 ≤ Node.val ≤ 9
  • The tree has at most 10 levels.
  • The answer is at most 231 − 1, so it fits in a 32-bit int.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.