数据结构中二叉树的遍历主要分为先序,中序和后序。顺序是相对根节点来说的。
先序中序非递归实现比较简单,后序较为复杂些,需要判断右子树是否为空或遍历完。
以下为三种遍历方法的非递归C实现
# include <stdio.h>
# include <stdlib.h>
typedef struct BiNode
{
char data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
typedef struct Bstack
{
BiTree bnode[30];
int top;
}Bstack;
void Initstack(Bstack *B)
{
int i;
for(i=0;i<30;++i)
B->bnode[i]=NULL;
B->top=-1;
}
int Emptystack(Bstack B)
{
if(B.top==-1)
return 1;
else
return 0;
}
void pushstack(Bstack *B,BiTree a)
{
(*B).bnode[++(*B).top]=a;
}
void popstack(Bstack *B)
{
(*B).bnode[(*B).top]=NULL;
(*B).top--;
}
void gettop(Bstack B,BiNode **a)
{
*a=B.bnode[B.top];
}
/*BiNode * gettop(Bstack B)
{
return &(B.bnode[B.top]);
}*/
void CreateBTree(BiTree *T)
{
char ch;
scanf("\n%c",&ch);
if(ch=='#')
*T=NULL;
else
{
*T=(BiNode *)malloc(sizeof(BiNode));
(*T)->data=ch;
printf("\n请输入%c的左孩子:",ch);
CreateBTree(&((*T)->lchild));
printf("\n请输入%c的右孩子:",ch);
CreateBTree(&((*T)->rchild));
}
}
void PreOrderWithoutRecursion(BiTree T)
{
Bstack s;
Initstack(&s);
BiNode *p;
p=T;
printf("先序遍历二叉树顺序为:");
while(!Emptystack(s)||p)
{
if(p)
{
printf("%c ",p->data);
pushstack(&s,p);
p=p->lchild;
}
else
{
gettop(s,&p);
p=p->rchild;
popstack(&s);
}
}
printf("\n");
}
void InOrderWithoutRecursion(BiTree root)
{
Bstack s;
Initstack(&s);
BiNode *p;
p=root;
pushstack(&s,p); p=p->lchild;
printf("中序遍历二叉树顺序为:");
while(!Emptystack(s)||p)
{
if(p)
{
pushstack(&s,p);
p=p->lchild;
}
else
{
gettop(s,&p);
printf("%c ",p->data);
popstack(&s);
p=p->rchild;
}
}
printf("\n");
}
void PostOrderWithoutRecursion(BiTree root)
{
Bstack s; Initstack(&s);
BiNode *pCur, *pLastVisit;
pCur = root;
pLastVisit = NULL;
printf("后序遍历二叉树顺序为:");
while (pCur)
{
pushstack(&s,pCur);
pCur = pCur->lchild;
}
while (!Emptystack(s))
{
gettop(s,&pCur);
popstack(&s);
if (pCur->rchild == NULL || pCur->rchild == pLastVisit)
{
printf("%c ",pCur->data);
pLastVisit = pCur;
}
else
{
pushstack(&s,pCur);
pCur = pCur->rchild;
while (pCur)
{
pushstack(&s,pCur);
pCur = pCur->lchild;
}
}
}
printf("\n");
}
int main()
{
BiTree btree;
CreateBTree(&btree);
PreOrderWithoutRecursion(btree);
InOrderWithoutRecursion(btree);
PostOrderWithoutRecursion(btree);
return 0;
}