Tree Recovery
Time limit1sMemory limit128 MB
Given a binary tree's preorder and inorder traversal strings, print its postorder traversal. Process runs until end of file.
- Level
Medium4 of 10
- Topics
- Tree, Recursion, Divide and conquer
- Solved
- No attempts yet
Problem
Changyoung loves binary trees. His favorite pastime is to build a binary tree and write one uppercase letter on each node. No letter is used on more than one node, so every node carries a distinct letter.
Below is one example of a binary tree Changyoung built.
D
/ \
/ \
B E
/ \ \
/ \ \
A C G
/
/
F
So that he can rebuild a tree later, Changyoung writes it down on paper. He records the result of a preorder traversal and the result of an inorder traversal. For the tree above, the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG. Because these two traversals are enough to reconstruct the tree uniquely, he does not bother writing down the postorder traversal.
Years later he wants to rebuild the tree from the paper, but doing it by hand is tedious, so he decides to write a program. Given the preorder and inorder traversals of a tree, write a program that outputs its postorder traversal.
Input
The input consists of one or more test cases.
Each test case is a single line containing the preorder traversal and the inorder traversal of a tree, separated by a single space. The two strings always have the same length, consist only of uppercase letters, and are at most 26 characters long. Input continues until end of file (EOF).
Output
For each test case, output the postorder traversal of the given tree on its own line.