Suppose that we have numbers between 1 and 1,000 in a binary search tree and…

2016

Suppose that we have numbers between 1 and 1,000 in a binary search tree and want to search for the number 364. Which of the following sequences could not be the sequence of nodes examined ?

  1. A.

    925, 221, 912, 245, 899, 259, 363, 364

  2. B.

    3, 400, 388, 220, 267, 383, 382, 279, 364

  3. C.

    926, 203, 912, 241, 913, 246, 364

  4. D.

    3, 253, 402, 399, 331, 345, 398, 364

Attempted by 336 students.

Show answer & explanation

Correct answer: C

Key idea: When searching for 364 in a binary search tree, each visited node imposes a range of allowed values for all subsequently visited nodes. If you go left at a node, the upper bound becomes that node's value; if you go right, the lower bound becomes that node's value. Track the interval (low, high) and verify each next node falls inside it.

  1. Sequence 925, 221, 912, 245, 899, 259, 363, 364 — possible.

    Reason: Start with bounds (1,1000). Visit 925 (364 < 925) -> new high = 925. Visit 221 (364 > 221) -> new low = 221. Visit 912 (221 < 912 < 925) -> go left to 245 (valid between 221 and 912), then right to 899 (between 245 and 912), left to 259 (between 245 and 899), right to 363 (between 259 and 899), then right to 364. All nodes respect the current bounds.

  2. Sequence 3, 400, 388, 220, 267, 383, 382, 279, 364 — possible.

    Reason: Start (1,1000). 3 -> right to 400 (364 < 400) -> left to 388 -> left to 220 -> right to 267 -> right to 383 -> left to 382 -> left to 279 -> right to 364. Each visited value lies within the interval determined by previous decisions.

  3. Sequence 926, 203, 912, 241, 913, 246, 364 — impossible.

    Reason: Start (1,1000). Visit 926 -> new high = 926. Visit 203 -> new low = 203. Visit 912 is valid (203 < 912 < 926) -> since 364 < 912 go left and after visiting 241 the new low becomes 241. The next visited node is 913, but 913 > 912, which violates the current upper bound 912. Therefore 913 cannot appear there and the sequence is not a valid BST search path for 364.

  4. Sequence 3, 253, 402, 399, 331, 345, 398, 364 — possible.

    Reason: Follow bounds: after 3 go right to 253, then right to 402, left to 399, left to 331, right to 345, right to 398, left to 364. All visited nodes satisfy the required intervals at each step.

Conclusion: The only sequence that could not occur during a BST search for 364 is the sequence containing 926, 203, 912, 241, 913, 246, 364 because 913 violates the upper bound established earlier.

Explore the full course: Coding For Placement