Problem Description:
Professor R. Borist studies trees. He has kept a record of the preorder, inorder, and postorder traversals of all of his favorite trees. However, a fire in his office has destroyed the file cabinet where he stored the inorder traversals. He still has the preorder and postorder traversals of all of his favorite trees, is this enough information to reconstruct the missing inorder traversals?
You must design and implement a program for the following task: The input will consist of two lists of numbers. The first list is the preorder traversal of some tree T. The second list is the postorder traversal of the same tree T. The output should be the inorder traversal of T. If the input does not determine a unique tree, then any consistent inorder traversal can be returned.
If it helps in designing your implementation, you can assume that:
- No tree has more than 1,000 nodes.
- No tree uses the same label for multiple nodes.
- Labels of nodes are numbers from 0 to 10,000.
Sample data
Input:
2 6 7 1 11 8 5 10 3 4 9
7 8 5 11 10 1 6 4 9 3 2
Output:
7 6 8 11 5 1 10 2 4 3 9
Hints
Given the preorder & postorder traversals of a tree, can you deduce which element was the root? which elements must have come from the left subtree? from the right subtree? Recurse.
First solve the problem when every node in the tree is guaranteed to have either 2 or 0 children. The case in which some nodes have only 1 child is a little trickier.
Notes
In your writeup, you do not need to analyze the efficiency / running time of your solution (this will be a requirement in future projects). But do analyze its correctness; i.e., explain clearly why your algorithm is correct.