二叉树遍历算法的非递归实现
标签:color 后序 its == node empty oid post int
1 void InOrder2(BTNode *root) {
2 BTNode *p = root;
3 stack 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 val " ";
12 p = p->right; // 访问双亲结点的右孩子
13 }
14 }
15 }
1 #include 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 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 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 }
二叉树遍历算法的非递归实现
标签:color 后序 its == node empty oid post int
原文地址:https://www.cnblogs.com/ruruozhenhao/p/13284822.html
评论