Question
A binary search tree contains distinct elements. What is the time complexity of picking an element in that is smaller than the maximum element in ?
Official answer and solution
- Official answer
- D
- From
- Official GATE 2021 answer key
Solution
Analyze which elements can be guaranteed to be smaller than the maximum element by inspecting only the root and its child pointers.
Let the root of the binary search tree be . By definition of a BST, all keys in the left subtree of any node are strictly smaller than , and all keys in the right subtree are strictly greater than .
Consider the root of (with distinct elements):
- If has a right child (), then the maximum element of resides somewhere in the right subtree of . Hence, is strictly smaller than the maximum element! We can simply return .
- If has no right child (), then itself is the maximum element of . Because , must have a non-empty left subtree. Any node in this left subtree is smaller than . In particular, the left child is strictly smaller than (the maximum element)! We can simply return .
In either case, we inspect only the root and its child pointers. No tree traversal or search is needed, taking constant time (option D).
D
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2021 Computer Science and Information Technology (CS, Set-1)
- Question
- 20 of 65, printed as CS Q.10
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.