二叉树的先序,中序,后序遍历的非递归算法

来源:互联网 发布:mysql数据库设计案例 编辑:程序博客网 时间:2024/04/30 14:40

关键是栈的运用,以此来模拟递归的过程

1.先序遍历非递归算法#define maxsize 100typedef struct{    Bitree Elem[maxsize];    int top;}SqStack;void PreOrderUnrec(Bitree t){    SqStack s;    StackInit(s);    p=t;       while (p!=null || !StackEmpty(s))    {        while (p!=null)             //遍历左子树        {            visite(p->data);            push(s,p);            p=p->lchild;              }//endwhile                if (!StackEmpty(s))         //通过下一次循环中的内嵌while实现右子树遍历        {            p=pop(s);            p=p->rchild;                }//endif                   }//endwhile   }//PreOrderUnrec2.中序遍历非递归算法#define maxsize 100typedef struct{    Bitree Elem[maxsize];    int top;}SqStack;void InOrderUnrec(Bitree t){    SqStack s;    StackInit(s);    p=t;    while (p!=null || !StackEmpty(s))    {        while (p!=null)             //遍历左子树        {            push(s,p);            p=p->lchild;        }//endwhile                if (!StackEmpty(s))        {            p=pop(s);            visite(p->data);        //访问根结点            p=p->rchild;            //通过下一次循环实现右子树遍历        }//endif          }//endwhile}//InOrderUnrec3.后序遍历非递归算法#define maxsize 100typedef enum{L,R} tagtype;typedef struct{    Bitree ptr;    tagtype tag;}stacknode;typedef struct{    stacknode Elem[maxsize];    int top;}SqStack;void PostOrderUnrec(Bitree t){    SqStack s;    stacknode x;    StackInit(s);    p=t;       do    {        while (p!=null)        //遍历左子树        {            x.ptr = p;            x.tag = L;         //标记为左子树            push(s,x);            p=p->lchild;        }           while (!StackEmpty(s) && s.Elem[s.top].tag==R)          {            x = pop(s);            p = x.ptr;            visite(p->data);   //tag为R,表示右子树访问完毕,故访问根结点              }                if (!StackEmpty(s))        {            s.Elem[s.top].tag =R;     //遍历右子树            p=s.Elem[s.top].ptr->rchild;                }       }while (!StackEmpty(s));}//PostOrderUnrec

层次遍历

int levelorder_traverse(bitree bt, int (*visit)(elemtype e)){sqqueuesq;bitreecur;init_queue(&sq);if (bt) {in_queue(&sq, bt);while (!is_queue_empty(sq)) {out_queue(&sq, &cur);visit(cur->data);if (cur->lchild)in_queue(&sq, cur->lchild);if (cur->rchild)in_queue(&sq, cur->rchild);}}return OK;}