PTA甲级考试真题练习127——1127 ZigZagging on a Tree

题目

在这里插入图片描述

思路

先利用后序和中序序列构造二叉树
然后利用BFS遍历二叉树,其中记录深度,深度为偶数的时候正序输出,否则逆序输出

代码

#include <iostream>
#include <vector>
using namespace std;
vector<int> in, post;
typedef struct node {
	int val;
	node* lchild, * rchild;
}*Tree;
void Init(Tree& root,int cur,int low,int high) {
	if (low > high)
		return;
	root = new node();
	root->val = post[cur];
	root->lchild = root->rchild = nullptr;
	int _index = low;
	while (_index <= high && in[_index] != post[cur]) _index++;
	int len = high - _index;
	Init(root->lchild,cur - 1 - len, low, _index - 1);
	Init(root->rchild,cur - 1, _index + 1, high);
}
void BFS(Tree& root) {
	queue<Tree> q;
	vector<int> vec;
	q.emplace(root);
	Tree cur = root;
	int depth = 1;
	while (!q.empty()) {
		Tree tmp = q.front();
		vec.emplace_back(tmp->val);
		q.pop();
		if (tmp->lchild != nullptr) 
			q.emplace(tmp->lchild);
		if (tmp->rchild != nullptr) {
			q.emplace(tmp->rchild);

		}
		if (tmp == cur) {
			if (tmp == root) {
				cout << tmp->val;
			}
			else {
				if (depth % 2 == 0) {
					for (int i = 0; i < vec.size(); ++i) 
						cout << " " << vec[i];
				}
				else {
					for (int i = vec.size() - 1; i >= 0; --i) 
						cout << " " << vec[i];
					
				}
			}
			vec.clear();
			if(!q.empty())
				cur = q.back();
			depth++;
		}
	}
}
int main()
{
	int n;
	cin >> n;
	in.resize(n);
	post.resize(n);
	for (int i = 0; i < n; ++i) cin >> in[i];
	for (int i = 0; i < n; ++i) cin >> post[i];
	Tree t = nullptr;
	Init(t,n-1,0,n-1);
	BFS(t);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值