Sum of Decimal Paths in a Binary Tree
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests depth-first (or breadth-first) traversal of a binary tree while tracking the accumulated digit value along each root-to-leaf path.
Problem Statement
You are given a binary tree where every node holds a single digit (0–9). Reading the digits from the root down to any leaf spells out a decimal number — the root digit is the most significant. For instance, travelling 3 → 1 → 4 produces the number 314.
Your task is to find the total of all such numbers, one per leaf.
The tree arrives as a level-order list (the same serialization format used by most online judges):
- The root is at index 0.
- For every non-null node dequeued in BFS order, the next two slots in the list are its left and right children.
Nonemarks an absent child.- Trailing
Nonevalues may be left out.
Return 0 for an empty or null-rooted tree.
Leaf Definition
A node is a leaf when both its left and right children are absent (i.e., None). A node with exactly one child is not a leaf; only the child's subtree contributes complete numbers.
Constraints
- The total number of nodes is in the range
[0, 1000]. - Every node value satisfies
0 ≤ value ≤ 9. - The tree depth will not exceed
10levels. - The sum of all path numbers fits in a standard Python integer.
Examples
Example 1
Input: path_digit_sum([1, 2, 3])
Output: 25
Example 2
Input: path_digit_sum([4, 9, 0, 5, 1])
Output: 1026
Example 3
Input: path_digit_sum([0, 1, 2])
Output: 3
Hints
Hint 1
Each time you move one level deeper, the number built so far shifts left by one decimal place: new_number = parent_number * 10 + child_digit. Think about how to carry that running value through your traversal.
Hint 2
Because the input is a level-order list, a BFS queue naturally processes nodes in the same order their child slots appear in the list. Keep a pointer into the list and advance it by two for every node you dequeue.
Hint 3
A node is a leaf only when both child slots are None. Make sure you test each slot with `is None` rather than a truthiness check, or a node with value 0 will be misidentified as absent.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Recurrence
Appending a digit d to the right of a number x is the same as x * 10 + d. So as we descend the tree, we carry a running value called prefix and update it at each node:
number_at_node = prefix * 10 + node_digit
When we reach a leaf (both children absent), number_at_node is the complete decimal number for that path, and we add it to the total.
Why BFS Fits This Input Format
The list is in level order. Children appear in the list in the same order their parents were enqueued — which is exactly FIFO order. This means a plain queue lets us match each dequeued node to its two consecutive child slots using a single advancing pointer index, without any arithmetic to locate children.
For each node we pop:
- Compute
number = prefix * 10 + value. - Read the next two list positions as left and right children, then advance
indexby 2. - If both children are
None, the node is a leaf — addnumbertototal. - Otherwise, enqueue whichever children exist, passing
numberas their new prefix.
Correctness
Number arithmetic: By induction on depth, the value carried to any node equals the decimal integer whose digits are the path from the root to that node. Each leaf is visited exactly once, so each path number is counted exactly once.
Child-slot assignment: The FIFO queue dequeues non-null nodes in the same order they appear as parents in the list. So root[index] and root[index+1] are always the correct left and right children of the current node. When index exceeds the list length, the children default to None, handling omitted trailing entries cleanly.
Edge Cases
- Empty input (
[],None, or[None]) → return0. - Single node
[7]→ it is a leaf, answer is7. - Zero digits: test with
is None, never bare truthiness, so0-valued nodes are never treated as absent. - A node with one child is not a leaf; only the subtree rooted at the existing child produces complete numbers.
Complexity
- Time: O(n) — each list element is read once; each node is enqueued and dequeued once.
- Space: O(w) — the queue holds at most one full level of the tree, where w is the maximum width. In the worst case this is O(n).
- Path numbers are at most 10 digits long (depth ≤ 10), so values stay well below 10¹⁰. With at most ~500 leaves the sum comfortably fits in any standard integer type.
Trace of [4, 9, 0, 5, 1]
4
/ \
9 0
/ \
5 1
| Pop | number | left slot | right slot | action | total |
|---|---|---|---|---|---|
| 4 | 4 | 9 | 0 | enqueue 9, 0 | 0 |
| 9 | 49 | 5 | 1 | enqueue 5, 1 | 0 |
| 0 | 40 | (none) | (none) | leaf, add 40 | 40 |
| 5 | 495 | (none) | (none) | leaf, add 495 | 535 |
| 1 | 491 | (none) | (none) | leaf, add 491 | 1026 |
Reference Solution
from collections import deque
from typing import List, Optional
def path_digit_sum(root: Optional[List[Optional[int]]]) -> int:
if not root or root[0] is None:
return 0
# Queue holds (node_value, number_built_so_far_by_ancestors)
nodes = deque([(root[0], 0)])
index = 1 # next unassigned child slot in the list
total = 0
while nodes:
value, prefix = nodes.popleft()
number = prefix * 10 + value
# The next two slots in level-order belong to this node's children.
left = root[index] if index < len(root) else None
index += 1
right = root[index] if index < len(root) else None
index += 1
if left is None and right is None: # leaf: path is complete
total += number
continue
if left is not None:
nodes.append((left, number))
if right is not None:
nodes.append((right, number))
return total