PTA甲级考试真题练习86——1086 Tree Traversals Again

题目

在这里插入图片描述

思路

使用前序遍历和中序遍历得到后序遍历,然后输出# 代码

#include <iostream>
#include <string>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> in, pre, post;
stack<int> s;
void postOrder(int root, int start, int end) {
	if (start > end)  return;
	int i = start;
	while (i < end && in[i] != pre[root]) ++i;
	postOrder(root + 1, start, i - 1);
	postOrder(root + i + 1 - start, i + 1, end);
	post.emplace_back(pre[root]);
}
int main()
{
	int n;
	cin >> n;
	string str;
	for(int i =0;i<2*n;++i){
		cin >> str;
		if (str == "Pop") {
			in.emplace_back(s.top());
			s.pop();
		}
		else{
			int num;
			cin >> num;
			s.push(num);
			pre.emplace_back(num);
		}
	}
	postOrder(0, 0, n - 1);
	cout << post[0];
	for (int i = 1; i < n; ++i)
		cout << " " << post[i];
	return 0;
}

发布了153 篇原创文章 · 获赞 4 · 访问量 3799

猜你喜欢

转载自blog.csdn.net/qq_43647628/article/details/105361011