GATE / CS ARCHIVE

GATE CSE 2013 / QUESTION 43

Recover BST postorder from preorder

Data Structures · Binary Search & Balanced Trees · Full GATE CSE 2013 paper

GATE 2013, Q43 2 marks · MCQ
Report issue

Binary Search & Balanced Trees

Question 43, GATE 2013: A BST has preorder 30, 20, 10, 15, 25, 23, 39, 35, 42. Choose postorder: A10, 20, 15, 23, 25, 35, 42, 39, 30; B15, 10, 25, 23, 20, 42, 35, 39, 30; C15, 20, 10, 23, 25, 42, 35, 39, 30; D15, 10, 23, 25, 20, 35, 42, 39, 30.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Step through it (21 steps)

The root is 30. Its preorder left-subtree segment is 20, 10, 15, 25, 23 and its right-subtree segment is 39, 35, 42. Under 20, node 10 has right child 15, and node 25 has left child 23; their postorders are 15, 10 and 23, 25, giving the full left-subtree postorder 15, 10, 23, 25, 20. Under 39 are children 35 and 42, so its postorder is 35, 42, 39. Appending the root gives 15, 10, 23, 25, 20, 35, 42, 39, 30, option D.

Preorder identifies each subtree’s root first. Split the remaining values around 30: values below 30 form the left subtree and above 30 the right. Repeat around 20 and 39. Postorder reverses the placement of each root in the traversal: recursively emit its left subtree, then right subtree, then the root. This yields left block 15, 10, 23, 25, 20 and right block 35, 42, 39, followed by 30. Checking only that 30 is last is insufficient; every nested subtree must satisfy the same rule.

Original paper, page 10 · Answer key