GATE / CS ARCHIVE

GATE CSE 2018 / QUESTION 20

Reconstructing a binary tree height

Data Structures · Tree Properties & Traversals · Full GATE CSE 2018 paper

GATE 2018, Q20 1 mark · NAT
Report issue

Tree Properties & Traversals

Question 20, GATE 2018: Postorder is 8,9,6,7,4,5,2,3,1 and inorder is 8,6,9,4,7,2,5,1,3. Height counts edges on a longest root-to-leaf path. Find the height.
Tap to enlarge
Answer & solution

Official answer: 4

Method

Postorder ends with the root, and inorder splits each subtree into left part, root, right part. Root 1 splits off right leaf 3. Its left subtree ends in 2, whose inorder split leaves right leaf 5 and left subtree rooted at 4. Continuing gives 4 with children 6 and 7, and 6 with children 8 and 9. There are five vertices but four edges on the longest path, so do not report the number of levels.

Solution

The final postorder element gives root1, with right child3 and left subtree rooted 2. In that left subtree, 5 is the right child, while 4 is the left child of 2; 4 has left child6 and right child7, and 6 has children 8, 9. A longest path is 1→2→4→6→8, four edges. Thus height 4.

Original paper, page 9 · Answer key