程序设计天梯赛L2-11 (给定树的前序和中序,求层次遍历)

题目
题意: RT.
思路: 用指针写,C++的指针还比C语言好写一点。这个是通用写法,如果权值各不相同直接用map维护就好了。
时间复杂度: O(n)
代码:

#include<bits/stdc++.h>
using namespace std;
int n,m,k,T;
const int N = 1e5+10;
struct node{
	int x;
	node*l;
	node*r;
};
node* newnode(int x)
{
	node *tmp = new node;
	tmp->x = x;
	tmp->l = NULL;
	tmp->r = NULL;
    return tmp;
}
int in[N];
int pre[N];
node* get(int l1,int r1,int l2,int r2)
{
	if(l1 > r1) return NULL;
	int idx;
	for(int i=l1;i<=r1;++i) if(in[i] == pre[l2]) idx = i;
	node*root = newnode(pre[l2]);
	int len = idx-l1;
	root->l = get(l1,idx-1,l2+1,l2+len);
	root->r = get(idx+1,r1,l2+len+1,r2);
	return root;
}
void bfs(node*root)
{
	queue<node*> q;
	q.push(root);
	// vector<int> va;
    while(q.size())
    {
    	node*tmp = q.front(); q.pop();
    	if(tmp == root)
    	{
    		cout<<tmp->x;
    	}
    	else cout<<" "<<tmp->x;
    	if(tmp->r != NULL) q.push(tmp->r);
    	if(tmp->l != NULL) q.push(tmp->l);
    }
}
void solve()
{
	cin>>n;
	for(int i=1;i<=n;++i) cin>>in[i];
	for(int i=1;i<=n;++i) cin>>pre[i];
	node *root = get(1,n,1,n);
	bfs(root);
}
signed main(void)
{
	solve();
	return 0;
}	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值