1 void PreOrder2(BTNode *root) {
2 BTNode *p = root;
3 stack<BTNode *> S;
4 while (p != NULL || !S.empty()) {
5 if (p) {
6 cout << p->val << " ";
7 S.push(p);
8 p = p->left;
9 } else {
10 S.pop();
11 p = S.top();
12 p = p->right;
13 }
14 }
15 }
1 void InOrder2(BTNode *root) {
2 BTNode *p = root;
3 stack<BTNode *> S;
4 while (p != NULL || !S.empty()) {
5 if (p) { // 找到树中最左边的那个结点,并将路径中经过的结点依次压入栈中
6 S.push(p);
7 p = p->left;
8 } else { // 如果该节点为空则输出其双亲结点
9 S.pop();
10 p = S.top();
11 cout << p->val << " ";
12 p = p->right; // 访问双亲结点的右孩子
13 }
14 }
15 }
1 #include <bits/stdc++.h>
2
3 using namespace std;
4
5 const int maxsize = 1005;
6
7 typedef struct BTNode {
8 int val;
9 BTNode *left;
10 BTNode *right;
11 };
12
13 typedef struct {
14 BTNode *p;
15 int revisited;
16 } SNode;
17
18 void PostOrder2(BTNode *root) {
19 SNode sn;
20 BTNode *pt = root;
21 stack<SNode> S;
22 while (pt) {
23 S.push({pt, 0});
24 pt = pt->left;
25 }
26 while (!S.empty()) {
27 sn = S.top();
28 if (sn.p->right == NULL || sn.revisited == 1) {
29 S.pop();
30 cout << pt->val << " ";
31 } else {
32 sn.revisited = 1;
33 pt = sn.p->right;
34 while (pt != NULL) {
35 S.push({pt, 0});
36 pt = pt->left;
37 }
38 }
39 }
40 }