团体天梯 L2-006 树的遍历 (25 分)(STL层序遍历、运行流程)

L2-006 树的遍历 (25 分)

给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

输入样例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

输出样例:

4 1 6 3 5 7 2

根据后序和中序遍历建树的程序步骤:

    1、从后序遍历中取最后一个结点

    2、在中序遍历中找到该结点

    3、以该结点为界线,将中序遍历一分为二,得到两个中序序列

    4、根据中序的分组,再回到后序遍历中将之一分为二,得到两个后序序列

    5、对于每个非空序列,回到第一步,继续执行

如果你想深入了解运行流程,可以加入print函数,恢复被我注释掉的print

print函数:

void print(Order order) {
	cout << "\n中序: ";
	for (auto it : order.mid)
		cout << it << " ";
	cout << "\n后序: ";
	for (auto it : order.post)
		cout << it << " ";
	cout << endl;
}

代码(通过分割): 

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct Order {
	vector<int> post, mid;
};
void creat(Order order) {
	queue<Order> tree;
	tree.push(order);
	while (!tree.empty()) {
		Order left, right;
		int  key = tree.front().post.back(), flag = 0;
	//print(tree.front());
		for (int i = 0, j = 0; i < tree.front().mid.size() && j < tree.front().post.size() - 1;) {
			if (tree.front().mid[i] == key) {
				i++; flag = 1;
			}
			else {
				(flag ? right : left).mid.push_back(tree.front().mid[i++]);
				(flag ? right : left).post.push_back(tree.front().post[j++]);
			}
		}
		if (!left.post.empty())			tree.push(left);
		if (!right.post.empty())		tree.push(right);
		tree.pop();
		cout << key << (tree.empty() ? "" : " ");
	}
}
int main() {
	int n, tmp;
	Order order;
	cin >> n;
	for (int i = 0; i < 2 * n; i++) {
		cin >> tmp;
		(i < n ? order.post: order.mid ).push_back(tmp);
	}
	creat(order);
	return 0;
}

通过划分:

#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
struct Range {
	pair<int,int> post, mid; //[left,right)
};
int main() {
	int n, tmp;
	vector<int> post, mid;
	cin >> n;
	for (int i = 0; i < 2 * n; i++) {
		cin >> tmp;
		(i < n ? post : mid).push_back(tmp);
	}
	queue<Range> tree;
	tree.push({ { 0,n }, { 0,n } });
	while (!tree.empty()) {
		Range left, right,head=tree.front();
		int key=post[head.post.second-1];
		int midindex = distance(mid.begin(), find(mid.begin()+head.mid.first, mid.begin()+head.mid.second, key));
		left.mid = { head.mid.first,midindex };
		right.mid = { midindex + 1,head.mid.second };
		int len = midindex - head.mid.first;
		left.post = { head.post.first,head.post.first+len };
		right.post = { head.post.first + len,head.post.second - 1 };
		if (left.post.second>left.post.first)			tree.push(left);
		if (right.post.second>right.post.first)		tree.push(right);
		tree.pop();
		cout << key << (tree.empty() ? "" : " ");
	}
	return 0;
}

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值