Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1328124
  • 博文数量: 281
  • 博客积分: 8800
  • 博客等级: 中将
  • 技术积分: 3345
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-17 22:31
文章分类

全部博文(281)

文章存档

2013年(1)

2012年(18)

2011年(16)

2010年(44)

2009年(86)

2008年(41)

2007年(10)

2006年(65)

我的朋友

分类: C/C++

2006-08-14 11:42:36

二叉树三种遍历的非递归算法
本贴给出二叉树先序、中序、后序三种遍历的非递归算法,此三个算法可视为标准算法,直接用于考研答题。kaoyangj
1.先序遍历非递归算法
#define maxsize 100
typedef 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
   
}//PreOrderUnrec
2.中序遍历非递归算法
#define maxsize 100
typedef 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
}//InOrderUnrec
3.后序遍历非递归算法
#define maxsize 100
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同济
阅读(1426) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~