Data Structures and Algorithms
The values 1, 2, 3, …, 1000 are inserted in this order into an empty binary search tree (no rebalancing is done). When searching this tree for 1000, how many nodes are compared, starting from the root, before it is found?
- A10
- B500
- C1,000
Show answer and explanation
Answer: C. 1,000
When values are inserted in ascending order, each new value becomes the right child of the previous maximum, so the tree becomes a single chain extending only to the right (height 999). 1000 is at the very bottom, so it is compared with all 1,000 nodes, 1, 2, …, 1000, which is O(n), the same as walking a linked list from the front. A balanced tree would have only about log₂ 1000 ≈ 10 levels, so using a self-balancing binary search tree such as an AVL tree or a red-black tree, which reshapes itself on every insertion and deletion, keeps the worst case at O(log n).
- A. A balanced tree would need about 10, but this tree has become a single chain.
- B. This is close to searching for a value in the middle, but 1000 is at the end.
- C. Correct. The tree is a single chain, so finding 1000 means comparing every node.