1.先序遍历非递归算法
voidPreOrderUnrec(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
}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.中序遍历非递归算法
voidInOrderUnrec(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
}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
}
posted on 2013-11-20 11:02 ** 阅读(105) 评论(0) 编辑 收藏