Question
Suppose a binary search tree with 1000 distinct elements is also a complete binary tree. The tree is stored using the array representation of binary heap trees. Assuming that the array indices start with 0, the 3rd largest element of the tree is stored at index_____________.
Official answer and solution
- Official answer
- 509
- From
- Official GATE 2022 answer key
Solution
Identify the positions of the top three largest elements in a binary search tree that has a complete binary tree heap layout.
The tree has 1000 nodes indexed to in array representation, where for node , its left child is and right child is .
In a complete binary tree with 1000 nodes:
- The first 9 levels (level 0 to 8) are completely full, containing nodes, spanning indices to .
- Level 9 contains the remaining nodes, occupying indices to .
Since the tree is also a Binary Search Tree (BST), the in-order traversal visits nodes in strictly increasing sorted order.
- Node 510 has children at and , which are both , so 510 is a leaf.
- The parent of node 510 is . Node 510 is the right child of node 254 ().
- The left child of node 254 is . Node 509 has children at and , so 509 is also a leaf.
Now observe the rightmost portion of the BST:
- Node 254 has no ancestors to its right because is the right child of , which is the right child of , and so on up to the root.
- Therefore, the subtree rooted at node 254 contains the largest elements of the entire BST.
- In the subtree at node 254, the in-order traversal visits: left child (node 509), root (node 254), right child (node 510).
- Thus, the 3 largest elements of the tree in increasing order are: node 509 (3rd largest), node 254 (2nd largest), and node 510 (1st largest).
Hence, the 3rd largest element is stored at index 509.
509
Assuming the 3rd largest element must be an ancestor on the right spine rather than the left child of the 2nd largest node.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2022 Computer Science and Information Technology (CS)
- Question
- 28 of 65
- 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.