Predict the output
Inserting sorted keys into a plain search tree. What does this print?
def height_after_inserts(keys: list[int]) -> int:
tree: dict[int, list[int | None]] = {}
root: int | None = None
best = 0
for k in keys:
if root is None:
root, tree[k], best = k, [None, None], 1
continue
cur, d = root, 1
while True:
side = 0 if k < cur else 1
nxt = tree[cur][side]
d += 1
if nxt is None:
tree[cur][side] = k
tree[k] = [None, None]
break
cur = nxt
best = max(best, d)
return best
chain = height_after_inserts(list(range(10)))
bushy = height_after_inserts([5, 2, 8, 1, 3, 7, 9, 0, 4, 6])
print(chain, bushy)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 10 4
Right: sorted inserts make a chain of 10, a good order gives height 4.
The same ten keys give very different heights depending on insert order, which is why balancing matters.
Why not the others?
- B 4 4. Sorted inserts always go right, building a chain.
- C 10 10. The mixed order spreads keys on both sides.