nyoj756 重建二叉树

重建二叉树

时间限制: 1000 ms  |  内存限制: 65535 KB
难度: 3
描述
题目很简单,给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!)。
输入
输入有多组数据(少于100组),以文件结尾结束。
每组数据仅一行,包括两个字符串,中间用空格隔开,分别表示二叉树的后序和中序序列(字符串长度小于26,输入数据保证合法)。
输出
每组输出数据单独占一行,输出对应得先序序列。
样例输入
ACBFGED ABCDEFG
CDAB CBAD
样例输出
DBACEGF
BCAD

思路:看到本题首先想到的是重建一个二叉树,由中序遍历和后序遍历可以重新构建一颗二叉树,然后先序遍历输出求的结果

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
char num;
struct node *lchild,*rchild;
}NODE,*PNODE;
void buildTree(PNODE * root,char*post,char*in,int len)/*root表示根节点,post表示后序遍历的结果,in表示中序遍历的结果,len表示当前子树的长度*/ 
{
	if(len==0)
	{
		*root=NULL;
	     return;
	}
	PNODE node=(PNODE)malloc(sizeof(NODE));
	node->num=post[len-1];
	node->lchild=node->rchild=NULL;
	*root=node;
	char *s=strchr(in,node->num);//找到根节点在中序遍历中的位置 
	int leftlen=strlen(in)-strlen(s);//左子树的长度 
	int rightlen=len-leftlen-1;//右子树的长度 
	buildTree(&(*root)->lchild,post,in,leftlen);//递归建左子树 
	buildTree(&(*root)->rchild,post+leftlen,s+1,rightlen);//递归建立右子树 
}
void bianliTree(PNODE root)//先序遍历 
{
	if(root==NULL)
		return ;
	printf("%c",root->num);
    bianliTree(root->lchild);
	bianliTree(root->rchild);
}
int main()
{
	char post[26],in[26];
    while(scanf("%s %s",post,in)!=EOF)
	{
		PNODE root=NULL;
		buildTree(&root,post,in,strlen(in));
		bianliTree(root);
		printf("\n");
	}
	return  0;
}


AC过后看到大神的代码瞬间泪奔太简单了根本不用重建二叉树,只需要每次把求得的结果输出即可!

大神代码:

#include<stdio.h>
#include<string.h>
void ReBuild(char *pre, char *in,char *post, int len)
{
	if(len>0)
	{
		int n =strchr(in,post[len-1])-in;
		ReBuild(pre+1,in,post,n);
		ReBuild(pre+n+1,in+n+1,post+n,len-n-1);
		pre[0]=post[len-1];
	}
}
int main()
{
	char pre[30],in[30],post[30];
	int len;
	while(~scanf("%s%s",post,in))
	{
		len=strlen(post);
		ReBuild(pre,in,post,len);
		pre[len]=0;
		puts(pre);
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值