GATE / CS ARCHIVE

GATE CSE 2021 SET 1 / QUESTION 10

GATE CSE 2021 Set 1 Q10

Data Structures · Binary Search & Balanced Trees · Full GATE CSE 2021 Set 1 paper

GATE 2021 Set 1, Q10 1 mark · MCQ
Report issue

Binary Search & Balanced Trees

Question 10, GATE 2021: A binary search tree T has n distinct elements. What is the time complexity of picking an element smaller than its maximum? A Θ(n log n); B Θ(n); C Θ(log n); D Θ(1). The task implicitly requires n≥2.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

If the root has a right child, the root itself is smaller than the maximum. If it has no right child, it is the maximum, so return its left child. For n≥2 that child exists in the latter case. Only a constant number of pointer tests is needed, Θ(1), D. The task implicitly needs at least two nodes; no such element exists for n=1.

An O(1) algorithm is: if root.right is non-null, return root.key; otherwise return root.left.key. In the first branch some right-subtree key is greater than the root, proving the root is not maximum. In the second branch the root is maximum; distinctness ensures its left child is strictly smaller. Searching for the second-largest element would be a different, potentially height-dependent task; the question asks for any smaller element.

Original paper, page 16 · Answer key