Every node in a binary tree, starting from root, holds a single digit from 0 to 9. Reading the digits along a path from the root down to a leaf (a node with no children) spells out a number: the path 4 → 1 → 6 is the number 416.
Add up the numbers for every root-to-leaf path and return the total. The total is small enough to fit in a 32-bit integer.
Example 1
Input: root = [5, 2, 7, 3] Output: 580 Why: the paths spell 523 and 57, and 523 + 57 = 580
2 more examples and the constraints
Example 2
Input: root = [0, 1, 8] Output: 9 Why: the paths spell 01 and 08, which are 1 and 8
Example 3
Input: root = [6] Output: 6 Why: the root is also the only leaf
Constraints
- The tree has between 1 and 1,000 nodes
- 0 ≤ each node value ≤ 9
- The tree is at most 10 levels deep
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Collect digit stringsO(n·h)
- DFS carrying the numberO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a tree of 1,000 nodes | Verdict |
|---|---|---|---|
| Collect digit strings | O(n·h) | Passes; builds strings | |
| DFS carrying the number | O(n) | Best; one integer per call |
n = number of nodes, h = height of the tree (at most 10).
Edge cases to test
- A single node. [6] is both root and leaf: the answer is 6.
- Zero at the root. [0, 1, 8] spells 01 and 08, which count as 1 and 8.
- A node with one child. [3, 0] has one path, 30. The 3 is not a leaf, so it must not add 3 on its own.
- Ten levels deep. A path of ten digits, such as 1999999999, still fits in a 32-bit integer when the total does.
Common mistakes
- Adding
curwhen reaching an empty child instead of at a leaf, which double counts nodes with two children and counts one-child nodes. - Adding the digit before multiplying (
cur + node.val * 10), which builds the number backwards. - Sharing one path list across calls and forgetting to remove the digit on the way back up.
How to talk through it
- 1Clarify. Is a leaf a node with no children? Can a node hold 0? Will the total fit in an int?
- 2Give the simple version. Collect each path as a digit string and add them at the end.
- 3Replace the string with a number. Appending a digit is
cur * 10 + digit, so pass one integer down instead. - 4Code the DFS. Empty node returns 0, a leaf returns cur, any other node returns the sum of its children.
- 5Test out loud. Run a single node, a root of 0 and a node with only one child.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?