已知前序中序遍历,求树的后续遍历

本文介绍了一种根据先序遍历和中序遍历序列重建二叉树的方法,并展示了如何通过这些信息来实现后序遍历的打印。通过递归地划分二叉树,文章详细解释了重建过程中的关键步骤。

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

#define M 100
struct BTN
{
	int value;
	struct BTN* left;
	struct BTN *right;
};
int pre[8]={1,2,4,7,3,5,6,8};
int mid[8]={4,7,2,1,5,3,8,6};
int n=8;

struct BTN *rebuild(int k,int l,int r)
{
	if(k>=n||l>r)
		return NULL;
	struct BTN *root=new struct BTN;
	root->value=pre[k];
	root->left=root->right=NULL;
	for(int i=l;i<=r;i++)
	{
		if(mid[i]==pre[k])
		{
			root->left=rebuild(k+1,l,i-1);
			root->right=rebuild(k+1+i-l,i+1,r);
			return root;
		}
	}
}

struct BTN *rebuild_after(int n)
{

	return rebuild(0,0,n-1);
}

void after_print(struct BTN *root)
{
	if(root==NULL)
		return ;
	after_print(root->left);
	after_print(root->right);
	printf("%d ",root->value);
}


int main()
{
	string s;
	n=8;
	struct BTN *root=rebuild_after(n);
	after_print(root);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值