Question

A binary search tree TT contains nn distinct elements. What is the time complexity of picking an element in TT that is smaller than the maximum element in TT?

Choose one option
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 TT be rr. By definition of a BST, all keys in the left subtree of any node uu are strictly smaller than uu, and all keys in the right subtree are strictly greater than uu.

Consider the root rr of TT (with n≥2n \ge 2 distinct elements):

  1. If rr has a right child (r.right≠NULLr.\text{right} \neq \text{NULL}), then the maximum element of TT resides somewhere in the right subtree of rr. Hence, rr is strictly smaller than the maximum element! We can simply return rr.
  2. If rr has no right child (r.right==NULLr.\text{right} == \text{NULL}), then rr itself is the maximum element of TT. Because n≥2n \ge 2, rr must have a non-empty left subtree. Any node in this left subtree is smaller than rr. In particular, the left child r.leftr.\text{left} is strictly smaller than rr (the maximum element)! We can simply return r.leftr.\text{left}.

In either case, we inspect only the root and its child pointers. No tree traversal or search is needed, taking Θ(1)\Theta(1) constant time (option D).

Final answer

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.