Worst-case BST search — Aptitude Question
Worst-case BST search: What is the worst-case time complexity of searching for a key in a binary search tree… Answer and worked solution on CodeKairo.
- Topic: Data Structures & Algorithms
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 45 seconds
Question
What is the worst-case time complexity of searching for a key in a binary search tree holding n keys?
Options
- O(1)
- O(log n)
- O(n)
- O(n log n)
Show the answer and the worked solution
Correct answer: C. O(n)
Worked solution
- Each comparison moves one level down, so the cost equals the height of the tree.
- A balanced BST has height about log n, but inserting keys in sorted order gives every node only a right child.
- That degenerate chain has height n − 1, so the worst case is O(n).
Answer: O(n).
The idea
An unbalanced BST is just a linked list with extra pointers. Self-balancing variants such as AVL and red-black trees exist precisely to keep the height at O(log n).
Shortcut. Worst case means worst shape: keys inserted in sorted order make a chain of height n − 1, so a search can take O(n).
Common trap. "O(log n)" is the balanced or average case, guaranteed only by self-balancing trees such as AVL, not by a plain BST.
All Data Structures & Algorithms questions · placement mock tests