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 00 to 999999 in array representation, where for node ii, its left child is 2i+12i+1 and right child is 2i+22i+2.

In a complete binary tree with 1000 nodes:

  • The first 9 levels (level 0 to 8) are completely full, containing ∑k=082k=29−1=511\sum_{k=0}^8 2^k = 2^9 - 1 = 511 nodes, spanning indices 00 to 510510.
  • Level 9 contains the remaining 1000−511=4891000 - 511 = 489 nodes, occupying indices 511511 to 999999.

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 2(510)+1=10212(510)+1 = 1021 and 2(510)+2=10222(510)+2 = 1022, which are both >999> 999, so 510 is a leaf.
  • The parent of node 510 is ⌊(510−1)/2⌋=254\lfloor(510-1)/2\rfloor = 254. Node 510 is the right child of node 254 (2×254+2=5102 \times 254 + 2 = 510).
  • The left child of node 254 is 2×254+1=5092 \times 254 + 1 = 509. Node 509 has children at 2(509)+1=1019>9992(509)+1 = 1019 > 999 and 2(509)+2=1020>9992(509)+2 = 1020 > 999, so 509 is also a leaf.

Now observe the rightmost portion of the BST:

  • Node 254 has no ancestors to its right because 254254 is the right child of 126126, which is the right child of 6262, 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.

Final answer

509

Common trap

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.