1127 ZigZagging on a Tree (30 分)

44 篇文章 0 订阅

题目大意:给定一个中序和后序序列,求层次遍历,注意不是普通的层次,这个题目的输出要求是每隔一层要逆序输出。

正常中后序建树,数据范围小就可以不用哈希表优化建树,然后宽搜一遍把层次遍历存一下,然后将需要逆序的层翻转一下就行了。

#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 1000;
int post[N],iner[N],f,c;
vector<int>ans[100];
struct node
{
	int v;
	node *left,*right;
	node(int x) : v(x),left(NULL),right(NULL){}
}*tr;
node *build(int postL,int postR,int inL,int inR)
{
	if(postL > postR) return NULL;
	node * t = new node(post[postR]);
	int k = inL;
	while(post[postR] != iner[k]) k ++;
	t->left = build(postL,postL + k - inL - 1,inL,k - 1);
	t->right = build(postL + k - inL,postR - 1,k + 1,inR);
	return t;
}
void bfs(node *tr)
{
	queue<pair<node*,int>>que;
	que.push({tr,0});
	while(que.size())
	{
		auto x = que.front();que.pop();auto t = x.first;
		f = x.second;
		ans[x.second].push_back(t->v);
		if(t->left != NULL) que.push({t->left,x.second + 1});
		if(t->right != NULL ) que.push({t->right,x.second + 1});
	}
}
int main()
{
	int n;
	cin >> n;
	for(int i = 0; i < n; i ++) cin >> iner[i];
	for(int i = 0; i < n; i ++) cin >> post[i];
	tr = build(0,n - 1,0,n - 1);
	bfs(tr);
	for(int i = 0; i <= f; i ++)
		if(i % 2 == 0) reverse(ans[i].begin(),ans[i].end());
	for(int i = 0; i <= f; i ++)
		for(auto t : ans[i])
		{
			if(c != 0) cout << ' ';
			cout << t;c = 1;
		}
	
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值