Exercise 2: Boundary Keys Found Directly at the Root — Possible Solution ==================================================================== THE TEST ------------------------------ root.keys = [10, 20] # from the chapter's own hand-built tree for bk in [10, 20]: # trace btree_search(root, bk) by hand RESULT ------------------------------ btree_search(root, 10) -> 'v10' (returned directly from root, no descent) btree_search(root, 20) -> 'v20' (returned directly from root, no descent) TRACING key=10 ------------------------------ i = 0 while i < 2 and 10 > root.keys[i]: # root.keys[0] = 10 i += 1 # 10 > 10 is False -- loop body never runs # i is still 0 if i < 2 and 10 == root.keys[0]: # 10 == 10 -- True return root.values[0] # returns 'v10' HERE The while loop's own condition (`key > node.keys[i]`) is a strict greater-than -- it stops advancing i the instant it finds a key that is NOT strictly less than the target. Since 10 is not greater than 10, the loop exits immediately with i=0, and the very next check (`key == node.keys[i]`) succeeds right away. TRACING key=20 ------------------------------ i = 0 while i < 2 and 20 > root.keys[i]: # i=0: 20 > 10 -- True -> i becomes 1 # i=1: 20 > root.keys[1] = 20 -- False -- loop stops # i is now 1 if i < 2 and 20 == root.keys[1]: # 20 == 20 -- True return root.values[1] # returns 'v20' HERE Here the loop DOES advance once (past the smaller key 10), but stops correctly the moment it reaches 20 itself, since 20 is not strictly greater than 20. Again, the equality check on the very next line succeeds immediately, and the function returns before ever reaching the `if node.leaf: return None` line or the final recursive `btree_search(node.children[i], key)` call. WHY THIS WORKS AS AN ANSWER ------------------------------ Both traces confirm the same structural fact: the `key == node.keys[i]` check happens BEFORE the leaf check and BEFORE any recursive descent, at every single level of the tree, including the root. A key that happens to be stored directly in an internal node (as a promoted boundary key, exactly like 10 and 20 here) is found and returned at that level, with the function never even asking whether it's a leaf or looking at any child at all -- descending into a child only happens when the equality check has already failed.