二叉树 1

来源:互联网 发布:fpga与单片机速度 编辑:程序博客网 时间:2024/05/21 21:01
/*
题目1078:二叉树遍历
题目描述:
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
输入:
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
输出:
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
样例输入:
ABC
BAC
FDXEAG
XDEFAG
样例输出:
BCA
XEDGAF
*/
#include <stdio.h>
#include <string.h>
struct node{//树结点结构体
node *lchild;//左儿子指针
node *rchild;//右儿子指针
char c;//结点字符信息
}tree[50];//静态内存分配数组
int loc;//静态数组中已经分配的结点个数
node *create(){//申请一个结点空间,返回指向其的指针
tree[loc].lchild = tree[loc].rchild = NULL;//初始化左右儿子为空
return &tree[loc++];//返回指针,且loc累加
}
char str1[30],str2[30];//保存前序和中序遍历结果字符串
void postorder(node *t){//后序遍历
if(t->lchild != NULL){//若左子树不为空
postorder(t->lchild);//递归遍历左子树
}
if(t->rchild != NULL){//若右子树不为空
postorder(t->rchild);//递归遍历右子树
}
printf("%c",t->c);//遍历该结点,输出其字符信息


}
node *build(int s1, int e1, int s2, int e2){
//由字符串的前序遍历和中序遍历还原树,并返回其根节点,其中前序遍历结果为由
//str1[s1]到str1[e1],中序遍历结果为str2[s2]到str2[e2]
node* ret = create();//为该树根结点申请空间
ret->c = str1[s1];//该结点字符为前序遍历中第一个字符
int rootldx;
int i;
for(i=s2;i<=e2;i++){
//查找该根节点字符在中序遍历中的位置
if(str2[i] == str1[s1]){
rootldx = i;
break;
}
}
if(rootldx != s2){//若左子树不为空
ret->lchild = build(s1+1,s1+(rootldx-s2),s2,rootldx-1);
//递归还原其左子树
}
if(rootldx != e2){//若右子树不为空
ret->rchild = build(s1+(rootldx-s2)+1,e1,rootldx+1,e2);
//递归还原其右子树
}
return ret;//返回根节点指针
}
int main(){
while(scanf("%s",str1) != EOF){
scanf("%s",str2);//输入
loc = 0;//初始化静态内存空间中已经使用结点个数为0
int l1 = strlen(str1);
int l2 = strlen(str2);//计算两个字符串长度
node *t = build(0,l1-1,0,l2-1);
//还原整棵树,其根节点指针保存在t中
postorder(t);//后序遍历
printf("\n");//输出换行
}


return 0;
}
0 0