二叉树的遍历:先序、中序、后序
先序遍历的算法
- 先访问根结点
- 先序遍历左子树
- 先序遍历右子树
void PreOrder(BiTree root)
{
if(root!=NULL)
{
printf("%c",root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
中序遍历的算法
- 中序遍历左子树
- 访问根结点
- 中序遍历右子树
void InOrder(BiTree root)
{
if(root!=NULL)
{
InOrder(root->lchild); //访问左子树
printf("%c",root->data); //访问根结点
InOrder(root->rchild); //访问右子树
}
}
后序遍历的算法
- 后序遍历左子树
- 后序遍历右子树
- 访问根结点
void PostOrder(BiTree root)
{
if(root!=NULL)
{
PostOrder(root->lchild);
PostOrder(root->rchild);
printf("%c",root->data);
}
}
一、统计叶子结点数目
方法1:LeafCount为全局变量,在调用前初始化值为0
int LeafCount=0;
void LeafNum(BiTree root)
{
if(root!=NULL)
{
if(root->lchild==NULL && root->rchild==NULL)
LeafCount++;
LeafNum(root->lchild);
leafNum(root->rchild);
}
}
方法2:采用函数返回值
int leaf(BiTree root)
{
int LeafCount;
if(root==NULL)
LeafCount=0;
else if((root->lchild==NULL) && (root->rchild==NULL))
LeafCount=1;
else
LeafCount=leaf(root->lchild)+leaf(root->rchild);
return LeafCount;
}
二、计算二叉树的高度
求二叉树的高度
方法1:
int depth=0;
void PreTreeDepth(BiTree root, int h)
{
if(root!=NULL)
{
if(h>depth)
depth=h;
PreTreeDepth(root->lchild, h+1);
PreTreeDepth(root->rchild, h+1);
}
}
方法2:
int PostTreeDepth(BiTree root)
{
int hl, hr, max;
if(root!=NULL)
{
hl=PostTreeDepth(root->lchild);
hr=PostTreeDepth(root->rchild);
max=hl>hr?hl:hr;
return max+1;
}
else
return 0;
}
三、二叉树的非递归遍历
中序遍历的非递归算法
void InOrder(BiTree root)
{
SqStack S;
InitStack(S);
BiNode *P;
p=root;
while(p || !StackEmpty(S))
{
if(p)
{
Push(S,p); //保存根结点
p=p->lchild; //遍历左子树
}
else
{
Pop(S,p); //弹出根结点
visit(p->data); //访问根结点
p=p->rchild; //遍历右子树
}
}
}
先序遍历的非递归算法
void PreOrder(BiTree root)
{
SqStack S;
InitStack(S);
BiNode *p;
p=root;
while(p || !StackEmpty(S))
{
if(p)
{
visit(p->data);
Push(S,p);
p=p->lchild;
}
else
{
Pop(S,p);
p=p->rchild;
}
}
}
后序遍历的非递归算法
void PostOrder(BiTree root)
{
BiTree p=root, r=NULL;
SqStack S;
InitStack(S);
while(p || !StackEmpty(S))
{
if(p)
{
Push(S,p);
p=p->lchild;
}
else
{
p=GetTop(S);
if(p->rchild!=NULL && p->rchild != r) //右子树存在,且未被访问
p=p->rchild;
else
{
pop(S,p);
visit(p->data);
r=p; //记录最近已经访问过的结点
p=NULL: //结点访问完后,重置p指针
}
}
}
}