二叉樹前序、中序、後序三種遍曆的非遞迴演算法

來源:互聯網
上載者:User

一。教科書標準演算法
1.先序遍曆非遞迴演算法
void PreOrderUnrec(Bitree *t)
{
    Stack s;
    StackInit(s);
    Bitree *p=t;
   
    while (p!=NULL || !StackEmpty(s))
    {
        while (p!=NULL)             //遍曆左子樹
        {
            visite(p->data);
            push(s,p);
            p=p->lchild;  
        }
        
        if (!StackEmpty(s))         //通過下一次迴圈中的內嵌while實現右子樹遍曆
        {
            p=pop(s);
            p=p->rchild;        
        }//endif
               
    }//endwhile 
}

2.中序遍曆非遞迴演算法
void InOrderUnrec(Bitree *t)
{
    Stack s;
    StackInit(s);
    Bitree *p=t;

    while (p!=NULL || !StackEmpty(s))
    {
        while (p!=NULL)             //遍曆左子樹
        {
            push(s,p);
            p=p->lchild;
        }
        
        if (!StackEmpty(s))
        {
            p=pop(s);
            visite(p->data);        //訪問根結點
            p=p->rchild;            //通過下一次迴圈實現右子樹遍曆
        }//endif   
   
    }//endwhile
}

3.後序遍曆非遞迴演算法
typedef 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

二。前序最簡潔演算法
void PreOrderUnrec(Bitree *t)
{
   Bitree *p;
   Stack s;
   s.push(t);

   while (!s.IsEmpty())
   {
      s.pop(p);
      visit(p->data);
      if (p->rchild != NULL) s.push(p->rchild);
      if (p->lchild != NULL) s.push(p->lchild);
   }
}

三。後序演算法之二
void BT_PostOrderNoRec(pTreeT root)
{
stack<treeT *> s;
pTreeT pre=NULL;

while ((NULL != root) || !s.empty())
{
if (NULL != root)
{
s.push(root);
root = root->left;
}
else
{
root = s.top();
if (root->right!=NULL && pre!=root->right){
root=root->right;
}
else{
root=pre=s.top();
visit(root);
s.pop();
root=NULL;
}
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.