中序后序转二叉树

对于后序遍历,最后一个节点是根节点。

对于中序遍历,根节点的左边是左子树,根节点的右边是右子树。

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<map>
#include<vector>
#include<set>
#include<cmath>
#include<deque>
#include<queue>
#define int long long
#define endl "\n"

using namespace std;

struct node
{
	int data,left,right;
};

vector<int> in,post;
vector<node> T;
map<int,int> mp;
int p=-1;
//中序后续建二叉树 
int build(int inL,int inR,int postL,int postR)
{
	if(inL>inR || postL>postR) return -1;
	int data=post[postR];
	int idx=mp[data];
	int pos=++p;
	int l=idx-inL;
	
	T[pos].data=data;
	T[pos].left=build(inL,idx-1,postL,postL+l-1);
	T[pos].right=build(idx+1,inR,postL+l,postR-1);
}

//先序遍历 
void dfs(int k)
{
	cout<<T[k].data<<" ";
	if(T[k].left!=-1)
	{
		dfs(T[k].left);
	}
	if(T[k].right!=-1)
	{
		dfs(T[k].right);
	}
}

//层次遍历
void bfs()
{
	queue<int> q;
	q.push(0);
	while(q.size())
	{
		int x=q.front();
		q.pop();
		cout<<x<<" ";
		if(T[x].left!=-1)
			q.push(T[x].left);
		if(T[x].right!=-1)
			q.push(T[x].right);
	}
} 

void solve()
{
	int N;cin>>N;
	for(int i=0;i<N;i++)
	{
		int x;cin>>x;
		mp[i]=x;
		in.push_back(x);
	}
	for(int i=0;i<N;i++)
	{
		int x;cin>>x;
		post.push_back(x);
	}
	
	build(0,N-1,0,N-1);
}

signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	int T=1;//cin>>T;
	while(T--) solve();
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值