Home 二叉树三种遍历方式的非递归写法
Post
Cancel

二叉树三种遍历方式的非递归写法

前序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void PreOrderTraverse(BiTree T) {
    BiTree p = T;
    stack<BiTree> s;
    while (p || !s.empty()) {
        if (p) {
            visit(p);
            s.push(p);
            p = p->lchild;
        } else {
            p = s.top();
            s.pop();
            p = p->rchild;
        }
    }
}

中序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void InOrderTraverse(BiTree T) {
    BiTree p = T;
    stack<BiTree> s;
    while (p || !s.empty()) {
        if (p) {
            s.push(p);
            p = p->lchild;
        } else {
            p = s.top();
            s.pop();
            visit(p);
            p = p->rchild;
        }
    }
}

后序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void PostOrderTraverse(BiTree T) {
    BiTree p = T, lastVisit = T;
    stack<BiTree> s;
    while (p || !s.empty()) {
        if (p) {
            s.push(p);
            p = p->lchild;
        } else {
            p = s.top();
            if (p->rchild && p->rchild != lastVisit) {
                p = p->rchild;
            } else {
                s.pop();
                visit(p);
                lastVisit = p;
                p = nullptr;
            }
        }
    }
}
This post is licensed under CC BY 4.0 by the author.