Question
The postorder traversal of a binary tree is 8,9,6,7,4,5,2,3,1. The inorder traversal of the same tree is 8,6,9,4,7,2,5,1,3. The height of a tree is the length of the longest path from the root to any leaf. The height of the binary tree above is ______.
Official answer and solution
- Official answer
- 4
- From
- Official GATE 2018 answer key
Solution
Reconstruct the unique binary tree from its postorder and inorder traversals, then count edges along the deepest branch.
Given traversals:
- Postorder: 8, 9, 6, 7, 4, 5, 2, 3, 1
- Inorder: 8, 6, 9, 4, 7, 2, 5, 1, 3
Reconstruct the tree recursively:
- The root is the last element of postorder: 1.
- In inorder, 1 splits into left subtree and right subtree .
- Node 3 is a single right child of 1 (depth 1).
- Left subtree postorder is , so root of left subtree is 2.
- In inorder, 2 splits into left subtree and right subtree . Node 5 is right child of 2 (depth 2).
- Subtree has root 4 (last in postorder 8, 9, 6, 7, 4).
- In inorder, 4 splits into left subtree and right child 7 (depth 3).
- Subtree has root 6 (last in postorder 8, 9, 6).
- In inorder, 6 splits into left child 8 and right child 9 (both at depth 4).
The path from root 1 to leaf 8 is: .
The length of this path (number of edges) is 4. Hence, the height of the binary tree is 4.
4
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2018 Computer Science and Information Technology (CS)
- Question
- 30 of 65, printed as CS Q.20
- 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.