Description
Little Valentine liked playing with binary trees very much. Her favorite game is constructing randomly looking binary trees with capital letters in the nodes.
This is a example of one of her creations:
D / / B E /\ / \ \ A C G / / F
To record hers trees for the future generations, she wrote down the strings for each tree:a preorder traversal (root, left Sub Tree, right subtree) and a inorder traversal (left subtree, root, right subtree).
For the tree drawn above the preorder traversal are DBACEGF and the inorder traversal is ABCDEFG.
She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried I T).
Now, years later, looking again in the strings, she realized that reconstructing the trees is indeed possible, but only B Ecause she never had used the same letter twice in the same tree.
However, doing the reconstruction by hand, soon turned off to be tedious.
So now she asks you to write a program this does the job for her!
Input SpecificationThe input file is contain one or more test cases. Each test case consists of one line containing the strings Preord and Inord, representing the preorder traversal and Inord ER traversal of a binary tree. Both strings consist of unique capital letters. (Thus they is not longer than characters.)
Input is terminated by end of file.
Output SpecificationFor each test case, recover Valentine's binary tree and print one line containing the tree's Postorder traversal (left Sub Tree, right subtree, root).
Sample Input
DBACEGF Abcdefgbcad Cbad
Sample Output
Acbfgedcdab
Ideas:
The title will tell you the preamble and the middle order of a binary tree, and ask for its post-order
Pre-order: Middle, left, right
Middle order: Left, middle, right
Post: Left, right, middle
First observe
DBACEGF ABCDEFG
Because the previous one is the pre-order, so just can be determined by the first element of the tree's heel, and then in the middle order to find the location of the root, just as well as the middle sequence traversal of the tree into the Saozi right subtree, and then the tree to do similar recursive processing, you can clear a tree.
Finally, the post-sequential traversal, can be written in the form of recursion, but do not forget to determine whether the tree is in the end, or the program will be wrong
#include"Iostream"#include"String.h"UsingNamespace Std;struct Node{Char data;struct Node*lchild;struct Node*rchild;};struct Node*Buildtree(Char*pre,Char*in,int Len){struct Node*p;Char*q; P=New(struct Node);int k=0;If(len==0)Return NULL; P->data=*pre;For(q=in; q<in+len; q++){If(*q==*pre)Break; K++;} p->lchild=Buildtree(Pre+1, inK); P->rchild=Buildtree(Pre+1+kQ+1Len-K-1);Return P;}voidPost(struct Node*p){If(p!=null){Post(p->lchild);Post(p->rchild); cout<<p->data;}}IntMain(){Char A[100],b[100];While(CIN>>a>>b) { struct node*root; root=buildtree(a, b ,strlen(a)); post(root); cout<<endl; } return 0;}
Traversing a binary tree