原题链接:1086 Tree Traversals Again (25 分)
题目大意:
通过使用栈可以以非递归方式实现二叉树的中序遍历。
分析:
第一个是根节点
push 上一个是push 左儿子
上一个是pop 右儿子
满分代码:
#include <iostream>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int MAXN = 1e3+10;
int n;
int tr[MAXN], w[MAXN];
int l[MAXN], r[MAXN];
/*
第一个是根节点
push 上一个是push 左儿子
上一个是pop 右儿子
*/
// 这个dfs过程可以模拟成一颗递归树来看
void dfs(int u, int root) {
// cout << u << endl;
// 如果遍历到了叶子结点的孩子
if(!u) return;
dfs(l[u], root);
dfs(r[u], root);
cout << u;
if(u != root) cout << " ";
}
int main() {
cin >> n;
int root;
// type=0 代表push type=1 代表pop
int last = 0, type;
stack<int> stk;
for(int i = 0; i < 2 * n; i++) {
string op;
cin >> op;
if(op == "Push") {
int x;
cin >> x;
if(!last) {
root = x;
} else {
// 如果上一个点是push
if(type == 0) l[last] = x;
else r[last] = x;
}
stk.push(x);
last = x;
type = 0;
} else {
last = stk.top();
stk.pop();
type = 1;
}
}
dfs(root, root);
return 0;
}