树:前中后序互求

本文介绍了如何通过给定的二叉树中序和前序/后序遍历序列来重建二叉树并打印其相应的后序/前序遍历序列。文章提供了完整的C语言实现代码,包括递归算法步骤及其实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由前中序求后序

思路:

1 确定根,确定左子树,确定右子树。

2 在左子树中递归。

3 在右子树中递归。

4 打印当前根。

#include<stdio.h>
#include<string.h>
#define max 100
void rebuild(char *pre,char *in,int len);
int main()
{
	char pre[max],in[max];
	while(~scanf("%s%s",pre,in))
	{
		rebuild(pre,in,strlen(pre));
		printf("\n");
	}
	return 0;
}
void rebuild(char *pre,char *in,int len)
{
	char root1;
	root1=*pre;
	if(len==0)
		return ;
	int root;
	for(root=0;root<len;root++)
		if(in[root]==root1)//区分左右子树
			break;
	rebuild(pre+1,in,root);//左子树
	rebuild(pre+root+1,in+root+1,len-root-1);//柚子树,roo+1为左子树的长度
	printf("%c",root1);
}

知中后序求前原理:

1 确定根,确定左子树,确定右子树。

2 在左子树中递归。

3 在右子树中递归。

4 打印当前根。

#include<stdio.h>
#include<string.h>
#define max 100
void rebuild(char *post,char *in,int len);
int main()
{
	char post[max],in[max];
	while(~scanf("%s%s",post,in))
		rebuild(post,in,strlen(in));
	return 0;
}
void rebuild(char *post,char *in,int len)
{
	char root1;
	if(len==0)//特殊情况
		return ;
	root1=*(post+len-1);//最后一个就是根,后基本规则
	printf("%c",root1);
	int root;
	for(root=0;root<len;root++)
		if(in[root]==root1)
			break;
	rebuild(post,in,root);//左子树
	rebuild(post+root,in+root+1,len-root-1);//右子树
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值