题意
用栈的形式给出一棵二叉树的建立的顺序,求这棵二叉树的后序遍历
观察二叉树可以发现,先序遍历就是push的顺序,中序遍历就是pop的顺序。
注意点
一开始以为是很常规的先序和中序建树,然后后序遍历就行。但是提交之后发现没有通过,分析原因是因为当有重复的值的时候,中序遍历的数组无法分辨哪一个是根节点。解决:通过指针。
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
output
3 4 2 6 5 1
#pragma GCC optimize(2)
#include"bits/stdc++.h"
using namespace std;
struct Node {
int v = 0;
Node *l = nullptr;
Node *r = nullptr;
Node(int v) : v(v) {}
};
vector<Node *> pre, in, pos;
void getPost(int l, int r, int root) {
if (l > r)
return;
int i;
for (i = l; i <= r; i++) {
if (in[i] == pre[root]) {
break;
}
}
getPost(l, i - 1, root + 1);
int numL = i - l;
getPost(i + 1, r, root + 1 + numL);
pos.push_back(pre[root]);
}
int main() {
//freopen("input.txt", "r", stdin);
int n;
cin >> n;
pre.reserve(n);
in.reserve(n);
stack<Node *> s;
for (int i = 0; i < 2 * n; ++i) {
string s1;
cin >> s1;
if (s1 == "Push") {
int v;
scanf("%d", &v);
Node *p = new Node(v);
s.push(p);
pre.push_back(p);
} else {
in.push_back(s.top());
s.pop();
}
}
getPost(0, n - 1, 0);
bool blank = false;
for (auto p:pos) {
if (blank) printf(" ");
else blank = true;
printf("%d", p->v);
}
}