Skip to content
Official PYQ · 1997

GATE CS 1997 Q4.5 — Binary Search Trees

Explain with AI

A binary search tree contains the value 1,2,3,4,5,6,7,81, 2, 3, 4, 5, 6, 7, 8. The tree is traversed in pre-order and the values are printed out. Which of the following sequences is a valid output?

Choose one option
View worked solution

Answer: D

For any node XX in a Binary Search Tree (BST), the pre-order traversal follows the Root →\rightarrow Left →\rightarrow Right strategy. This imposes a strict partitioning rule on the pre-order sequence:

  • The first element is the root XX.
  • All elements in the sequence following XX that are smaller than XX (representing the left subtree) must appear before any elements that are larger than XX (representing the right subtree).
  • This property must hold recursively for every subtree.

Let's analyze the options with the keys {1,2,3,4,5,6,7,8}\{1, 2, 3, 4, 5, 6, 7, 8\}:

  1. 5 3 1 2 4 7 8 65 \ 3 \ 1 \ 2 \ 4 \ 7 \ 8 \ 6
    • For root 55, the left subtree is {3,1,2,4}\{3, 1, 2, 4\} and the right subtree is {7,8,6}\{7, 8, 6\}.
    • For the right subtree root 77, the elements are 7 [8 6]7 \ [8 \ 6]. Here, 66 (smaller than 77) appears after 88 (larger than 77). This violates the BST property. Thus, this sequence is invalid.
  2. 5 3 1 2 6 4 8 75 \ 3 \ 1 \ 2 \ 6 \ 4 \ 8 \ 7
    • For root 55, the element 44 (smaller than 55) appears after 66 (larger than 55). This violates the partition property for root 55. Thus, this sequence is invalid.
  3. 5 3 2 4 1 6 7 85 \ 3 \ 2 \ 4 \ 1 \ 6 \ 7 \ 8
    • For root 55, the left subtree sequence is 3 2 4 13 \ 2 \ 4 \ 1.
    • For subtree root 33, the element 11 (smaller than 33) appears after 44 (larger than 33). This violates the partition property for root 33. Thus, this sequence is invalid.
  4. 5 3 1 2 4 7 6 85 \ 3 \ 1 \ 2 \ 4 \ 7 \ 6 \ 8
    • For root 55, the left subtree is {3,1,2,4}\{3, 1, 2, 4\} and the right subtree is {7,6,8}\{7, 6, 8\}.
    • For subtree root 33, the left subtree is {1,2}\{1, 2\} and the right subtree is {4}\{4\}. This is valid. For root 11, the right child is 22. This is valid.
    • For subtree root 77, the left subtree is {6}\{6\} and the right subtree is {8}\{8\}. This is valid.
    • Since all recursive partitions are valid, this sequence is valid.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Binary Search Trees questions