The Way of C++

  C++博客 :: 首页 :: 联系 :: 聚合  :: 管理
  55 Posts :: 0 Stories :: 19 Comments :: 0 Trackbacks

公告

The first time i use this blog, i will write something that i learn which i think is worth write down.

常用链接

留言簿(3)

我参与的团队

搜索

  •  

最新评论

阅读排行榜

评论排行榜

一。教科书标准算法
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;
}
}
}
}

posted on 2010-03-18 12:23 koson 阅读(288) 评论(0)  编辑 收藏 引用 所属分类: ACM

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理