Question

The number of ways in which the numbers 1, 2, 3, 4, 5, 6, 7 can be inserted in an empty binary search tree, such that the resulting tree has height 6, is ________.

Note: The height of a tree with a single node is 0.

Official answer and solution
Official answer
64
From
Official GATE 2016 answer key

Solution

Express the condition for a binary search tree to have maximum possible height as a choice between extreme keys at each step.

We are inserting the 7 distinct keys {1,2,3,4,5,6,7}\{1, 2, 3, 4, 5, 6, 7\} into an empty binary search tree.

The problem states that the height of a single-node tree is 0. A tree with n=7n = 7 nodes has height 6 if and only if the tree is completely degenerate (every internal node has exactly one child, forming a single chain or path of 7 nodes).

Analyze the conditions on the insertion sequence to form a degenerate BST:

  1. The first inserted key (the root) must be either the minimum element (1) or the maximum element (7) of the set. If any intermediate element were chosen, keys would fall on both sides of the root, creating both left and right subtrees and resulting in a height strictly less than 6. Thus, there are 2 choices for the root.
  1. After the first key is placed, the remaining 6 keys must form a single contiguous chain. At each step ii (for i=1,2,…,6i = 1, 2, \dots, 6), the next key to be inserted must again be either the minimum or the maximum of the currently remaining uninserted keys. This gives 2 choices at each step.
  1. For the final (7th) key, only 1 key remains, so there is 1 choice.

The total number of valid insertion permutations is:

Total ways=2×2×2×2×2×2×1=27−1=26=64\text{Total ways} = 2 \times 2 \times 2 \times 2 \times 2 \times 2 \times 1 = 2^{7-1} = 2^6 = 64
Final answer

64

Common trap

Computing only the two fully sorted orders (1, 2, 3, 4, 5, 6, 7 and 7, 6, 5, 4, 3, 2, 1) giving 2, missing zigzag degenerate trees.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2016 Computer Science and Information Technology (CS) Session 2
Question
50 of 65, printed as CS Q.40
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.