PAT|1086 Tree Traversals Again (二叉树遍历,重建)

题目大意

可以使用堆栈以非递归方式实现中序二叉树遍历。例如,假设遍历一棵6节点的二叉树(key从1到6编号)时,然后可以从这个操作序列生成一个唯一的二叉树。你的任务是给出这棵树的后序遍历序列。

解题关键

  • 本题给出了使用栈进行中序遍历的过程,我们要做的是由此得到二叉树的前序遍历和中序遍历,然后由此还原的二叉树,最后层次遍历即可。

代码

#include<bits/stdc++.h>
using namespace std;
struct TreeNode
{
	int val = 0;
	TreeNode* left = nullptr;
	TreeNode* right = nullptr;
};
int num;
vector<int> prevec, invec, postvec;
stack<int> sta;
map<int, int> inmap;
TreeNode* makeTree(int l1, int r1,int l2,int r2) {
	if (l1 > r1) {
		return nullptr;
	}
	TreeNode* root = new TreeNode();
	root->val = prevec[l1];
	int ind = inmap[prevec[l1]];
	root->left = makeTree(l1 + 1, l1 + (ind - l2), l2, ind - 1);
	root->right = makeTree(l1 + 1 + (ind - l2), r1, ind + 1, r2);
	return root;
}
void getPost(TreeNode* root) {
	if (root == nullptr) {
		return;
	}	
	getPost(root->left);
	getPost(root->right);
	postvec.push_back(root->val);
	return;
}
int main() {
	cin >> num;
	string str;
	int i = 0;
	while (i++ < num * 2) {
		cin >> str;
		if (str == "Push") {
			int tem;
			cin >> tem;
			prevec.push_back(tem);
			sta.push(tem);
		}
		else {//Pop
			invec.push_back(sta.top());
			sta.pop();
		}
	}
	for (int i = 0; i < invec.size(); i++) {
		inmap.emplace(invec[i], i);
	}
	TreeNode* root = makeTree(0, num - 1, 0, num - 1);
	getPost(root);
	for (int i = 0; i < postvec.size(); i++) {
		if (i == 0) {
			cout << postvec[i];
		}
		else {
			cout << ' ' << postvec[i];
		}
	}
	cout << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值