Rebuild binary tree
Time Limit:
1000
ms | Memory Limit:
65535
KB
Difficulty:
3
- describe
- The problem is very simple, give you the post-order and in-order sequence of a binary tree, and find its pre-order sequence (So easy!).
- enter
-
Enter multiple sets of data (less than 100 sets), ending with the end of the file.
Each set of data consists of only one line, including two strings, separated by spaces, representing the post-order and in-order sequences of the binary tree respectively (the length of the string is less than 26, and the input data is guaranteed to be legal). - output
- Each set of output data occupies a separate line, and the output corresponds to a pre-order sequence.
- sample input
-
ACBFGED ABCDEFG CDAB CBAD
- Sample output
-
DBACEGF BCAD
source
The first approach:
#include<stdio.h> #include<iostream> #include<algorithm> #include<stdio.h> using namespace std; struct Node{//Binary tree structure char data; Node * lchild; Node * rchild; }; Node *build(string hou,string in) { Node *root=NULL; if(hou.length()>0) { int k=hou.length(); root=new Node; root->data=hou[k-1];//The last visited root node of post-order traversal. int index=in.find(hou[k-1]);//Find the root node of the current tree in the inorder sequence root->lchild=build(hou.substr(0,index),in.substr(0,index));//Recursive left subtree root->rchild=build(hou.substr(index,k-1-index),in.substr(index+1));//Recursive right subtree //substr copies a substring, starting at the specified position and having the specified length. } return root; } void print(Node *root)//output sequence sequence { if(root!=NULL) { printf("%c",root->data);//Output the root node first post(root->lchild);//Revisit the left subtree post(root->rchild);//Finally visit the right subtree } } intmain() { string hou,in; while(cin>>hou>>in)//Read in post-order and in-order sequences { Node* root=build(hou,in);//Convert post-order and mid-order sequence to pre-order sequence print(root);//Preorder sequence recursive output cout<<endl; } return 0; }
The second method of the gods:
#include<stdio.h>
#include<string.h>
void ReBuild(char *pre,char *in,char *post,int len)
{
if(len>0)
{
int n=strchr(in,post[len -1])-in;//strchr function finds the first match of a given character in a string
ReBuild(pre+1,in,post,n);
ReBuild(pre+n+1,in+n +1,post+n,len-n-1);
pre[0]=post[len-1];
}
}
int main()
{
char pre[30],in[30],post[30];
int len;
while(~scanf("%s%s",post,in))
{
len=strlen(post);
ReBuild(pre,in,post,len);
pre[len]=0;
puts(pre);
}
return 0;
}