Fill the blank
Fill the blank so each round handles exactly one row.
from collections import deque
level = [8, 3, 10, 1, 6, None, 14]
kids = {i: [j for j in (2 * i + 1, 2 * i + 2)
if j < len(level) and level[j] is not None]
for i in range(len(level))}
q = deque([0])
out = []
while q:
row = []
for _ in range(____):
i = q.popleft()
row.append(level[i])
q.extend(kids[i])
out.append(row)
print(out)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A len(q)
Right: the queue holds exactly the current row when the round starts.
Reading the queue length once, before children are added, separates the rows.
Why not the others?
- B len(level). That tries to take every node in the first round.
- C 2. Rows double at most; a fixed count breaks on uneven trees.
Steps come from running the Python solution.
Text version
level order:
Tree:
- 8
- 3 (left)
- 1 (left)
- 6 (right)
- 4 (left)
- 7 (right)
- 10 (right)
- 14 (right)
- 3 (left)
- Visit 8
- Visit 3
- Visit 10
- Visit 1
- Visit 6
- Visit 14
- Visit 4
- Visit 7
Result: [[8], [3, 10], [1, 6, 14], [4, 7]]. Order: 8, 3, 10, 1, 6, 14, 4, 7
preorder:
Tree:
- 8
- 3 (left)
- 1 (left)
- 6 (right)
- 4 (left)
- 7 (right)
- 10 (right)
- 14 (right)
- 3 (left)
- Visit 8
- Visit 3
- Visit 1
- Visit 6
- Visit 4
- Visit 7
- Visit 10
- Visit 14
Result: [8, 3, 1, 6, 4, 7, 10, 14]. Order: 8, 3, 1, 6, 4, 7, 10, 14