递归
void preOrder(int root) {
if (!val[root]) {
return;
}
cout << val[root] << " ";
preOrder(ls[root]);
preOrder(rs[root]);
}
void inOrder(int root) {
if (!val[root]) {
return;
}
inOrder(ls[root]);
cout << val[root] << " ";
inOrder(rs[root]);
}
void afterOrder(int root) {
if (!val[root]) {
return;
}
afterOrder(ls[root]);
afterOrder(rs[root]);
cout << val[root] << " ";
}
非递归
#include <bits/stdc++.h>
using namespace std;
/*
10
/ \
5 8
/ \
3 9
/ \ \
3 5 25
/ \ / \
7 10 10 30
*/
int val[25];
int ls[25], rs[25];
stack<int> sk;
deque<int> de;
/*
* 前序
* 先push根结点, 然后对于每个栈顶结点, 先push右再push左
*/
void preOrder(int root) {
sk.push(root);
while (sk.size()) {
int cur = sk.top();
cout << val[cur] << " ";
sk.pop();
if (rs[cur]) {
sk.push(rs[cur]);
}
if (ls[cur]) {
sk.push(ls[cur]);
}
}
}
/*
* 中序
* 对于每个结点, 直接push它的左子树, 然后指针指向栈顶结点的右子树
*/
void InOrder(int root) {
int cur = root;
while (cur || !sk.empty()) {
while (cur) {
sk.push(cur);
cur = ls[cur];
}
cur = sk.top();
sk.pop();
cout << val[cur] << " ";
cur = rs[cur];
}
}
/*
* 前序交换入栈顺序 根 -> 右 -> 左
* 倒序 左 -> 右 -> 根
*/
void AftOrder(int root) {
sk.push(root);
while (sk.size()) {
int cur = sk.top();
de.push_front(val[cur]);
sk.pop();
if (ls[cur]) {
sk.push(ls[cur]);
}
if (rs[cur]) {
sk.push(rs[cur]);
}
}
while (de.size()) {
cout << de.front() << " ";
de.pop_front();
}
}
int main() {
val[1] = 10, val[2] = 5, val[3] = 8, val[4] = 3, val[5] = 9, val[6] = 3, val[7] = 5, val[8] = 25, val[9] = 7, val[10] = 10, \
val[11] = 10, val[12] = 10, val[13] = 30;
ls[1] = 2, rs[1] = 3, ls[2] = 4, rs[3] = 5, ls[4] = 6, rs[4] = 7, rs[5] = 8, ls[6] = 9, rs[7] = 10, ls[8] = 11, rs[8] = 13;
while (sk.size()) {
sk.pop();
}
// InOrder(1);
// in(1);
AftOrder(1);
return 0;
}