九度OJ - 1078:二叉树遍历
来源:《算法竞赛入门经典(第2版)》
标签:
参考资料:
相似题目:
题目
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
输入
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C….最多26个结点。
输出
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
输入样例
ABC
BAC
FDXEAG
XDEFAG
输出样例
BCA
XEDGAF
解题思路
参考代码1
//使用数组
#include<stdio.h>
#include<string.h>
const int maxn=30;
char s1[maxn],s2[maxn],s3[maxn];
int lch[maxn],rch[maxn];
int build(int L1,int R1,int L2,int R2)
{
if(L1>R1) return 0;
int root=s1[L1]-'A'+1;
int p=L2;
while(s2[p]-'A'+1!=root)p++;//在中序遍历中寻找根的位置
int cnt=p-L2;
lch[root]=build(L1+1,L1+cnt,L2,p-1);
rch[root]=build(L1+cnt+1,R1,p+1,R2);
return root;
}
int cnt;
void postOrder(int u)
{
if(lch[u])postOrder(lch[u]);
if(rch[u])postOrder(rch[u]);
s3[cnt++]=u+'A'-1;
}
int main()
{
while(scanf("%s%s",s1,s2)==2)
{
int len=strlen(s1);
build(0,len-1,0,len-1);
cnt=0;
postOrder(s1[0]-'A'+1);
s3[cnt]='\0';
printf("%s\n",s3);
}
return 0;
}
参考代码2
//使用结构体
#include<stdio.h>
#include<string.h>
const int maxn=30;
char s1[maxn],s2[maxn],s3[maxn];
struct Node{
char c;
Node *left;
Node *right;
Node():c(0),left(NULL),right(NULL){
}
};
Node* build(int L1,int R1,int L2,int R2)
{
if(L1>R1) return 0;
Node *root=new Node();
root->c=s1[L1];
int p=L2;
while(s2[p]!=root->c)p++;//在中序遍历中寻找根的位置
int cnt=p-L2;
root->left=build(L1+1,L1+cnt,L2,p-1);
root->right=build(L1+cnt+1,R1,p+1,R2);
return root;
}
int cnt;
void postOrder(Node *u)
{
if(u->left)postOrder(u->left);
if(u->right)postOrder(u->right);
s3[cnt++]=u->c;
}
int main()
{
while(scanf("%s%s",s1,s2)==2)
{
int len=strlen(s1);
Node *root=build(0,len-1,0,len-1);
cnt=0;
postOrder(root);
s3[cnt]='\0';
printf("%s\n",s3);
}
return 0;
}