Binary Trees Depth first: return a value up
360. Sum Root to Leaf Numbers
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
Input: root = [6, 1, 3, null, 4, 7, 9]
1890Explanation: 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
Input: root = [0, 5, 0, null, null, 2]
7Explanation: The paths spell 05 and 002, which are the numbers 5 and 2. A leading 0 adds nothing to a number.
Example 3
Input: root = [2, null, 0, 0]
200Explanation: 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.
Constraints
1 ≤ number of nodes ≤ 10230 ≤ 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.