An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.
Figure 1
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.
Output Specification:
For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
结尾无空行
Sample Output:
3 4 2 6 5 1
结尾无空行
分析:
思路一:
题意理解:根据题目条件可以得到该树的先序和中序遍历序列
push时候访问输出则是先序遍历,pop时访问输出则是后序遍历
先序、中序和后序遍历过程中经过结点的路线一样,只是访问各结点的时机不同
所以此题就转化成,已知先序和中序序列,求后序序列的题目:先得到线序与中序序列存储,再处理得到后序遍历序列
使用字符数组或者是string来解决都可以
姥姥讲解的伪代码:
格外注意:在写递归函数的时候要注意递归的最小规模边界的处理!!!
思路二:
由树的遍历知识总结可知,非递归的利用堆栈实现的先序、中序和后续遍历程序是非常相似的,只是访问输出节点的时机不同
所以,可以 直接在非递归遍历程序的基础上进行改造,增加计数器,实现后序遍历序列的输出
#include<iostream>
#include<vector>
#include<stack>
#include<string>
using namespace std;
int main() {
int N; cin>>N;
vector<int>visit(N+1, 0);
stack<int>state;
vector<int>ans;
int n = 2 * N-1;
string op; cin >> op;
while (n--) {
if (op == "Push") {
int x; cin >> x;
state.push(x); visit[x]++;
}
else if (op == "Pop") {
while (!state.empty() && visit[state.top()] == 2) {
int p = state.top(); state.pop();
ans.emplace_back(p);
}
visit[state.top()]++;
}
cin >> op;
}
while (!state.empty()) {
int p = state.top(); state.pop();
ans.emplace_back(p);
}
int flag = 0;
for (auto x : ans) {
if (flag)cout << " ";
cout << x; flag = 1;
}
}