二叉树后序遍历非递归

(后序遍历需要对每个结点设置一个标志位,标示此结点的右孩子是否已被访问.)

  1. 一直访问左孩子,直到NULL;
    2.栈顶是否有右孩子,若有,按1执行;若无,打印栈顶,出栈;
    操作过程中,维护一个对应的visitedRight栈.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<stack>
#include<queue>
using namespace std;

typedef int DATA_TYPE;

typedef struct node
{
DATA_TYPE data;
node *lch, *rch;
node()
{
data = 0;
lch = rch = 0;
}
} Node;

Node nodeList[100];

void print(Node *r)
{
if(r)
{
print(r->lch);
printf("%d", r->data);
print(r->rch);
}
}

Node *buildTree(DATA_TYPE dataArray[], int len)
{
for(int i=1; i<len; i++)
{
nodeList[i].data = dataArray[i];
if(i%2)
{
nodeList[i/2].rch = &nodeList[i];
}
else
{
nodeList[i/2].lch = &nodeList[i];
}
}
return &nodeList[1];
}

/**
* 后序遍历的非递归算法
*/
void postOrderTraversal(Node *r)
{
Node *p;
stack<Node*> s;
stack<bool> visitedRight;
bool flag;
while(!s.empty() || r)
{
if(r)
{
s.push(r);
visitedRight.push(false);
r = r->lch;
}
else if(!visitedRight.top() && s.top()->rch)
{
visitedRight.top()=true;
r=s.top()->rch;
}
else
{
printf("%d", s.top()->data);
s.pop();
visitedRight.pop();
}
}
}

int main()
{
DATA_TYPE dataArray[] = {0,1,2,3,4,5,6,7};
Node *root = buildTree(dataArray, sizeof(dataArray)/sizeof(DATA_TYPE));
// print(root);
postOrderTraversal(root);

return 0;
}