2021/3/28 树和二叉树 已知后序遍历和中序遍历,求前序遍历

【练习时间】2021/3/28
【题目名称】已知二叉树的后序遍历和中序遍历,求前序遍历
详细的算法请参照我的另一篇博客
2021/3/6 算法训练 绘制地图(已知数组先序和中序求后序序列)
在这里我们只需要改变cur_pos的初始值和每次运行的操作即可
我们知道后序遍历序列是左子树->右子树->根;所以我们需要先建立右子树而后建立左子树即可。cur_pos初始化为n-1,每次找到后自动减一,如果没找到加一,先建立右子树;
【源代码】

/*
8
4 7 5 2 8 6 3 1
4 2 7 5 1 8 6 3
*/
#include <iostream>
using namespace std;
struct BiNode 
{
	int data;
	BiNode *lchild;
	BiNode *rchild;
};
int post[100];
int mid[100];
int cur_pos;
int n;
int FindNode(int val,int start_mid,int end_mid)
{
	for(int i=start_mid;i<=end_mid;i++)
	{
		if(mid[i]==val)return i;
	}
	return -1;
}
BiNode *CreateTree(int start_mid,int end_mid)
{
	if(start_mid>end_mid||cur_pos<0)
	{
		if(start_mid>end_mid)cur_pos++;
		return NULL;
	}
	BiNode *bt=NULL;
	bt=new BiNode;
	bt->data=post[cur_pos];
	int pos=FindNode(post[cur_pos],start_mid,end_mid);
	if(pos!=-1)
	{
		cur_pos--;
		bt->rchild=CreateTree(pos+1,end_mid);
		cur_pos--;
		bt->lchild=CreateTree(start_mid,pos-1);
	}
	return bt;
}
void Pre(BiNode *bt)
{
	if(bt==NULL)return;
	else{
		cout<<bt->data<<" ";
		Pre(bt->lchild);
		Pre(bt->rchild);
	}
}
int main()
{
	cin>>n;
	for(int i=0;i<n;i++)
	cin>>post[i];
	for(int i=0;i<n;i++)
	cin>>mid[i];
	cur_pos=n-1;
	Pre(CreateTree(0,n-1));
	return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yozu_Roo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值