原题:
Little Valentine liked playing with binary trees very much. Her favorite game was constructing randomly
looking binary trees with capital letters in the nodes.
This is an example of one of her creations:
To record her trees for future generations, she wrote down two strings for each tree: a preorder
traversal (root, left subtree, right subtree) and an inorder traversal (left subtree, root, right subtree).
For the tree drawn above the preorder traversal is 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 it).
Now, years later, looking again at the strings, she realized that reconstructing the trees was indeed
possible, but only because she never had used the same letter twice in the same tree.
However, doing the reconstruction by hand, soon turned out to be tedious.
So now she asks you to write a program that does the job for her!
Input
The input file will contain one or more test cases.
Each test case consists of one line containing two strings ‘preord’ and ‘inord’, representing the
preorder traversal and inorder traversal of a binary tree. Both strings consist of unique capital letters.
(Thus they are not longer than 26 characters.)
Input is terminated by end of file.
Output
For each test case, recover Valentine’s binary tree and print one line containing the tree’s postorder
traversal (left subtree, right subtree, root).
Sample Input
DBACEGF ABCDEFG
BCAD CBAD
Sample Output
ACBFGED
CDAB
中文:
给你一个二叉树的先序遍历和中序遍历,给出后序遍历。(很经典哦)
#include <bits/stdc++.h>
using namespace std;
typedef struct node
{
struct node* lchild;
struct node* rchild;
char data;
}node,*Btree;
void build(Btree &t,string pre,string in)
{
if(pre.length()==0)
{
t=NULL;
return;
}
char root=pre[0];
int ind=in.find(root);
string lchild_in=in.substr(0,ind);
string rchild_in=in.substr(ind+1);
int lchild_len=lchild_in.length();
int rchild_len=rchild_in.length();
string lchild_pre=pre.substr(1,lchild_len);
string rchild_pre=pre.substr(1+lchild_len);
t=(Btree)malloc(sizeof(node));
if(t!=NULL)
{
t->data=root;
build(t->lchild,lchild_pre,lchild_in);
build(t->rchild,rchild_pre,rchild_in);
}
}
void post(Btree &t)
{
if(t!=NULL)
{
post(t->lchild);
post(t->rchild);
cout<<t->data;
}
}
int main()
{
ios::sync_with_stdio(false);
string p,i;
Btree t;
while(cin>>p>>i)
{
build(t,p,i);
post(t);
cout<<endl;
}
return 0;
}
非指针版本
#include <bits/stdc++.h>
using namespace std;
void build(int n,char *p,char *i,char *b)
{
if(n<=0)
return;
char r=p[0];
int ind=strchr(i,r)-i;
build(ind,p+1,i,b);
build(n-ind-1,p+ind+1,i+ind+1,b+ind);
b[n-1]=r;
}
int main()
{
ios::sync_with_stdio(false);
char p[1000],i[1000],b[1000];
while(cin>>p>>i)
{
int n=strlen(p);
build(n,p,i,b);
b[n]='\0';
cout<<b<<endl;
}
return 0;
}
解答:
在小白书上这道题是例题,无意间在紫书上发现了它,赶紧做掉~