树和二叉树2——遍历

(保留版权,欢迎转载。请注明原始链接:http://blog.csdn.net/markcnsc/article/details/8551143)

typedef struct _BT {
    struct _BT* lc;
    struct _BT* rc;
    int v;
} BT;

void visit (BT* p);

1 递归遍历 (中序为例)

void traverse_in_order (BT* p)
{
    if (!p) return;
    traverse_in_order (p->lc);
    visit (p);
    traverse_in_order (p->rc);
}

2 非递归遍历 

2.1 先序非递归

Knuth版:

void trv_pre_order (BT* h)
{
    static BT* s[N]; //#define N >= number of nodes 
    int i = -1;
    BT* p = h;
 
    while (p || i >= 0) {
        if (p) {
            visit (p);
            s[++ i] = p;
            p = p->lc;
        }
        else {
            p = s[i --];
            p = p->rc;
        }
    }
}

Sedgewick版:

void trv_pre_order (BT* h)
{
    static BT* s[N]; //#define N >= number of nodes
    int i = -1; 
    BT* p; 

    if (!h) return; 
    s[++ i] = h;
    while (i >= 0) {
        p = s[i --];
        visit (p);
        if (p->rc) 
            s[++ i] = p->rc; 
        if (p->lc) 
            s[++ i] = p->lc; 
    }
}

2.2 中序非递归

void trv_in_order (BT* h)
{
    static BT* s[N]; //#define N >= number of nodes 
    int i = -1;
    BT* p = h;
 
    while (p || i >= 0) {
        if (p) {
            s[++ i] = p;
            p = p->lc;
        }
        else {
            p = s[i --];
            visit (p);
            p = p->rc;
        }
    }
}

2.3 后序非递归

void trv_post_order (BT* h)
{
    static BT* s[N]; //#define N >= number of nodes 
    int i = -1;
    BT* p = h;
    BT* q = NULL;
    
    while (p || i >= 0) {
        if (p) {
            s[++ i] = p;
            p = p->lc;
        }
        else {
            p = s[i];
            if (!p->rc || p->rc == q) {
                i --;
                visit (p);
                q = p;
                p = NULL;
            }
            else {
                p = p->rc;
            }
        }
    }
}

3 层次遍历

void trv_level_order (BT* h)
{
    static BT* q[N]; //#define N >= number of nodes;
    int i = 0, j = 0;
    BT* p;
    
    if (!h) return;
    q[++ i] = h;
    while (i != j) {
        p = [j=(j+1)%N];
        visit (p);
        if (p->lc)
            q[i=(i+1)%N] = p->lc;
        if (p->rc)
            q[i=(i+1)%N] = p->rc;
    }
}
点赞