Use inorder and postorder traversal of a binary tree to determine the preorder sequence of the binary tree
1000(ms)
10000(kb)
2036 / 3818
Knowing inorder and preorder traversal of a binary tree can uniquely determine postorder traversal, knowing inorder and postorder traversal can uniquely determine preorder traversal, but knowing preorder and postorder, but not necessarily uniquely determining inorder traversal . Now it is required to output its pre-order traversal results according to the input in-order traversal results and post-order traversal results.
enter
The first row is in sequence The second line follows the sequence
output
The output is the preorder sequence obtained by traversing the binary tree
sample input
BFDAEGC FBGECA
Sample output
ABDFCEG
Idea: First find the last bit of the post-order traversal, this node is the head node, and then find the node in the in-order traversal node, the left side of the node is the left-pointing tree, and the right side is the right node. Then there is splitting this into two parts, recursively.
#include<iostream>
#include<string.h>#include<stdlib.h>
using namespace std;
typedef struct node
{
char data;
struct node *l,*r;
}Tree;
Tree *built(char *fina,char *mid,int n)
{
Tree *T;
char *p;
int k=0;
if(n==0) return NULL;//如果k=0说明没有左树
T=(Tree *)malloc(sizeof(Tree));
T->data=fina[n-1];
for(p=mid;p<mid+n;p++)
{
if(*p==fina[n-1]) break;
k++;//记录结点。
}
T->l=built(fina,mid,k);
T->r=built(fina+k,mid+k+1,n-k-1);
return T;
}
void print(Tree *&l)
{
if(l)
{
cout<<l->data;
print(l->l);
print(l->r);
}
}
int main()
{
char mid[1000],fina[1000];
cin>>mid>>fina;
Tree *l=built(fina,mid,strlen(mid));
print(l);
return 0;
}