题目大意
可以使用堆栈以非递归方式实现中序二叉树遍历。例如,假设遍历一棵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;
}