Total Value of Bit-Strings Along a Tree's Leaf Paths
Trees & GraphsAuto-graded · 22 test casesLast updated
Decode a level-order bit tree with skipped None slots, then sum the binary values read along each root-to-leaf path, testing BFS parsing and DFS with a running accumulator.
A binary tree stores a single bit (0 or 1) in each node. Walking from the root down to any leaf produces a string of bits. Treat that string as a binary number, where the root's bit is the most significant digit. For instance, the walk 1 -> 1 -> 0 gives binary 110, which equals 6.
Your task is to compute the total of the numbers produced by every root-to-leaf walk.
Input format
The tree is given as a list tree in level-order form:
tree[0]is the value of the root.- After that, the entries are consumed in consecutive pairs. Each node that is not
Nonetakes one pair, and nodes are served in the order in which they appear in the list (first the root, then the real nodes in the order they were listed, and so on). - In each pair, the first entry is that node's left child and the second is its right child. A
Noneentry means that child does not exist. - A
Noneentry is just a placeholder: it does not get a pair of its own. - Trailing
Nonevalues may be left out. If the list ends before a node's pair is read, that node (and every node after it in the order) has no children. If only one entry of a pair remains, it is the left child and the right child is absent.
Rules
- A leaf is a node with no children. Each leaf ends exactly one path.
- A node with exactly one child is not a leaf.
- Leading zeros are fine: the walk
0 -> 1 -> 1is binary011, which equals 3. - If the root has no children, there is one path, and the answer is the root's bit.
Task
Return the sum of the values of all root-to-leaf paths as an integer.
Constraints
- The tree has between 1 and 1,000 nodes, and
1 <= len(tree) <= 2001. tree[0]is neverNone.- Every non-
Noneentry is0or1. - Each root-to-leaf path has at most 31 nodes, so each path value is at most
2^31 - 1. - The expected answer is guaranteed to be at most
2^31 - 1.
Examples
Example 1
Input: sum_leaf_path_values([1, 1, 0, None, 1, 1])
Output: 12
Example 2
Input: sum_leaf_path_values([1, 0, None, 0, 1])
Output: 9
Example 3
Input: sum_leaf_path_values([0])
Output: 0
Hints
Hint 1
Before worrying about the sum, think about how to rebuild the tree. Heap-style indexing (children at 2i+1 and 2i+2) fails when None entries appear; consider a queue that holds only the real nodes.
Hint 2
When you step from a parent to a child, the number spelled so far changes by a simple rule: shift it left one bit and add the child's bit, i.e. value = value * 2 + bit.
Hint 3
Add the running value to the answer only at nodes that have neither a left nor a right child. A node with just one child must keep going down.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
There are two separate jobs: rebuild the tree from the list, then add up the path values.
Rebuilding the tree. The format hands out pairs of entries to the non-None nodes in the order those nodes appear. That is exactly a breadth-first queue:
- Put the root in the queue.
- Take the next node from the queue and read the next two list entries as its left and right children.
- Every entry that is not
Nonebecomes a new node, is linked to its parent, and is appended to the queue. - If the list runs out, the remaining nodes simply have no children.
Nodes are stored in parallel arrays (vals, left, right) with -1 meaning "no child".
Summing the paths. Reading bits from the most significant end, appending a bit transforms the value as new = old * 2 + bit. So we do a depth-first traversal using an explicit stack of (node, value_so_far) pairs. When we reach a node with no children, its value is the number spelled by the full path, and we add it to the total.
Why it is correct
- Parsing:
Noneentries never enter the queue, so they never consume a pair. Real nodes consume pairs in their listed order, which is exactly what the format specifies. Truncated lists are handled by the bounds checks. - Accumulation: By induction on depth, the value at a node is the binary number spelled from the root to it. The root's value is its own bit, and
acc * 2 + bitappends one bit on the right. Leading zeros are naturally handled. - Summation: Each node is visited exactly once, and a node is counted only when both children are absent, matching the definition of a leaf. A node with a single child continues downward and is never counted.
Complexity
- Time: O(L + n), where L is the list length and n the number of nodes. Since L is at most 2n + 1, this is O(n).
- Space: O(n) for the arrays, the queue, and the stack.
Reference solution
from typing import List, Optional
def sum_leaf_path_values(tree: List[Optional[int]]) -> int:
n_entries = len(tree)
vals = [tree[0]]
left = [-1]
right = [-1]
queue = [0]
qi = 0
i = 1
# Rebuild the tree: every real node takes the next two entries.
while qi < len(queue) and i < n_entries:
node = queue[qi]
qi += 1
for side in (0, 1):
if i >= n_entries:
break
v = tree[i]
i += 1
if v is not None:
vals.append(v)
left.append(-1)
right.append(-1)
idx = len(vals) - 1
if side == 0:
left[node] = idx
else:
right[node] = idx
queue.append(idx)
# DFS carrying the number spelled so far.
total = 0
stack = [(0, vals[0])]
while stack:
node, acc = stack.pop()
l, r = left[node], right[node]
if l == -1 and r == -1:
total += acc
continue
if l != -1:
stack.append((l, acc * 2 + vals[l]))
if r != -1:
stack.append((r, acc * 2 + vals[r]))
return total