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)?
- A. 40, 5 nodes
- B. 38, 5 nodes
- C. 38, 9 nodes
- 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.
Practise more Programming and Data Structures (GATE) questionsProgramming and Data Structures (GATE): notes and key points
More Programming and Data Structures (GATE) questions
- bool f(Node n) { if (!n) return true; if (n->l && n->l->k > n->k) return false; if (n->r && n->r->k < n->k) return false; return f(n->l)…
- In the BST obtained by inserting 40, 20, 60, 10, 30, 50, 5, 15, 3, 1, 25, 55, 57, 56 in order, how many nodes have a balance factor…
- A binary tree is stored in level order with null children written as : 1 2 3 4 5 6 7 8 (a null child still consumes a slot only if its…
- Non-negative numbers are stored as singly linked lists of digits with the least significant digit first. A = 9 -> 9 -> 8 -> 5 (the number…
- A priority queue is a sorted singly linked list (ascending). Insert scans from the head, comparing the new key with each node, and stops…
- Keys 1..7 form a max-heap stored in a 0-indexed array (children of i are 2i+1, 2i+2). The key 5 is the third largest. In how many…