Data Structures & AlgorithmsHardProduct company OA

Keys 50, 30, 70, 20, 40, 60, 80, 35, 45, 65 are inserted into an empty BST. A range query counts keys in [33, 62], pruning subtrees that cannot contain a key in range. What is the count, and how many nodes does the query visit (including the root)?

  1. A. 5 keys, 10 nodes visited
  2. B. 5 keys, 8 nodes visited
  3. C. 4 keys, 8 nodes visited
  4. D. 5 keys, 7 nodes visited

Correct answer: B. 5 keys, 8 nodes visited

In range: 35, 40, 45, 50, 60 → 5 keys. Visits: 50 (go both ways), 30 (30 < 33, so skip its left subtree, i.e. 20) → 40 → 35, 45; on the right 70 (70 > 62, skip its right subtree 80) → 60 → its right child 65 (60 < 62, so it must be checked). 50, 30, 40, 35, 45, 70, 60, 65 = 8 visits. Visiting every node is 10.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic