原文链接: 重建二叉树
上一篇: 求次数
下一篇: 二叉排序树 创建和 遍历
重建二叉树
http://acm.nyist.net/JudgeOnline/problem.php?pid=756
时间限制:1000 ms | 内存限制:65535 KB
难度:3
输入
输入有多组数据(少于100组),以文件结尾结束。
每组数据仅一行,包括两个字符串,中间用空格隔开,分别表示二叉树的后序和中序序列(字符串长度小于26,输入数据保证合法)。
输出
每组输出数据单独占一行,输出对应得先序序列。
样例输入
ACBFGED ABCDEFG CDAB CBAD
样例输出
DBACEGF BCAD
描述
题目很简单,给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!)。
#include <cstdio>
#include <cstring>
#include <cstdlib>
struct node
{
char value;
node *lchild,*rchild;//左孩子,右孩子
};
node *newnode(char c)
{
node *p=(node *)malloc(sizeof(node));
p->value=c;
p->lchild=p->rchild=NULL;
return p;
}
node *rebulid(char *post,char *in,int n)
{
if(n==0) return NULL;
char ch=post[n-1];//得到的是根节点的值
node *p=newnode(ch);
int i;
for(i=0;i<n&&in[i]!=ch;i++);
int l_len=i;
int r_len=n-i-1;
if(l_len>0) p->lchild=rebulid(post,in,l_len);//由中序遍历得出左右子树的值
if(r_len>0) p->rchild=rebulid(post + l_len, in+l_len+1, r_len);
return p;
}
void preorder(node *p)//先序遍历
{
if(p==NULL) return;
printf("%c",p->value);
preorder(p->lchild);
preorder(p->rchild);
}
int main()
{
char postorder[30],inorder[30];
while(scanf("%s%s",postorder,inorder)!=EOF)
{
node *root=rebulid(postorder,inorder,strlen(postorder));
preorder(root);
printf("\n");
}
return 0;
}