GATE Computer ScienceHardGATE CS (PYQ pattern)

Keys 50, 30, 70, 20, 40, 60, 80, 10, 25, 35, 45, 55, 65, 75, 85, 5, 22, 33, 38 are inserted in this order into an empty BST, and every node stores the size of its subtree. select(x, k) returns the k-th smallest key: with s = size of x's left subtree, it returns x's key if k == s + 1, recurses left if k <= s, and otherwise recurses right with k - s - 1. Which key does select(root, 9) return, and how many nodes does it visit (including the one returned)?

  1. A. 40, 5 nodes
  2. B. 38, 5 nodes
  3. C. 38, 9 nodes
  4. D. 35, 4 nodes

Correct answer: B. 38, 5 nodes

Sorted keys: 5 10 20 22 25 30 33 35 38 40 45 50 55 60 65 70 75 80 85, so the 9th smallest is 38. The search: root 50 has 11 keys on its left, so go left with k = 9; 30 has 5 on its left, go right with k = 9 - 6 = 3; 40 has 3 on its left (35, 33, 38), go left with k = 3; 35 has 1 on its left, go right with k = 1; 38 has 0 on its left, k == 1: found. Path 50 -> 30 -> 40 -> 35 -> 38: 5 nodes, instead of the 9 nodes an inorder count would touch.

More Programming and Data Structures (GATE) questions

Exams that ask this topic