nyist oj 756 重建二叉树

时间:2023-12-03 17:39:20

重建二叉树

时间限制:1000 ms  |  内存限制:65535 KB
难度:3
描写叙述
题目非常easy。给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!)。
输入
输入有多组数据(少于100组),以文件结尾结束。

每组数据仅一行,包含两个字符串。中间用空格隔开,分别表示二叉树的后序和中序序列(字符串长度小于26,输入数据保证合法)。
输出
每组输出数据单独占一行,输出相应得先序序列。
例子输入
ACBFGED ABCDEFG
CDAB CBAD
例子输出
DBACEGF
BCAD
来源
原创
上传者

TC_黄平

这道题主要考查对二叉树的遍历的熟悉程度,对先序遍历。中序遍历。后序遍历的掌握程度;

由后序遍历能够得到,最后一个字母应该就是树的根节点,中序遍历是先訪问左子树,后訪问根节点,在訪问右子树。然后通过中序遍历的序列。能够把这颗树分成左右子树。得出这颗树的结构,然后再递归得出先序遍历的序列。

以下是代码:

#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;
}