最近在复习数据结构,顺便看看大一的时候写的代码,看完之后比当初有了更加深刻的体会。
希望这些能提供给初学者一些参考。
1.二叉树遍历算法的递归实现
这个较为直观,但是效率不是太高
//1.先序遍历
void PreOrder (BinTree root)
{
if (root != NULL)
{
printf ("%c", root->data); //访问根结点
PreOrder (root->lchild); //先序遍历左子树
PreOrder (root->rchild); //先序遍历右子树
}
}
//2.中序遍历
void InOrder (BinTree root)
{
if (root != NULL)
{
Inorder(root->lchild); //中序遍历左子树
printf ("%c", root->data); //访问根结点
Inorder(root->rchild); //中序遍历右子树
}
}
//3.后序遍历
void PostOrder (BinTree root)
{
if (root != NULL)
{
PostOrder(root->lchild); //后序遍历左子树
PostOrder(root->rchild); //后序遍历右子树
printf ("%c", root->data); //访问根结点
}
}
2.二叉树遍历算法的非递归实现(注释可参考上面的)
后序遍历与先序、中序不太一样,要注意加深理解
#define MAXSIZE 100
//定义栈
typedef struct
{
BinTree elem[MAXSIZE];
int top;
}SeqStack;
//1.先序遍历
void PreOrder(BinTree root)
{
SeqStack s;
s.top=-1;
do
{
while(root!=NULL)
{
++s.top;
if(s.top==MAXSIZE-1)
{
printf("overflow!");
return;
}
s.elem[s.top]=root;
printf("%c ",root->data);
root=root->lchild;
}
if(-1!=s.top)
{
root=s.elem[s.top];
--s.top;
root=root->rchild;
}
}while(s.top!=-1 || root!=NULL);
}
//2.中序遍历
void InOrder (BinTree root)
{
SeqStack s;
s.top=-1;
do
{
while(root!=NULL)
{
++s.top;
if(s.top==MAXSIZE-1)
{
printf("overflow!");
return;
}
s.elem[s.top]=root;
root=root->lchild;
}
if(-1!=s.top)
{
root=s.elem[s.top];
printf("%c ",root->data);
--s.top;
root=root->rchild;
}
}while(s.top!=-1 || root!=NULL);
}
//3.后序遍历
void PostOrder(BinTree root)
{
SeqStack s;
s.top=-1;
do
{
while(root!=NULL)
{
++s.top;
if(s.top==MAXSIZE-1)
{
printf("overflow!");
return;
}
root->isFirst=true;
s.elem[s.top]=root;
root=root->lchild;
}
if(-1!=s.top)
{
root=s.elem[s.top];
if(root->isFirst&&root->rchild)
{
root->isFirst=false;
root=root->rchild;
}
else
{
printf("%c ",root->data);
--s.top;
root=NULL;
}
}
}while(s.top!=-1 || root!=NULL);
}