1.层次遍历算法
思想:层次遍历需要借助一个队列。先将二叉树的根节点入队,然后出队,访问出队结点,如果它有左子树,则将它的左子树根节点入队;若它有右子树,则将右子树根结点入队。然后出队访问出队节点如此往复,直到队列为空。
void LevelOrder(BiTree T){
LinkQueue Q;
InitQueue(Q);//初始化辅助队列
BiTree p;
EnQueue(Q,T);//将根结点入队
whlie(!IsEmpty(Q)){//队列不空则循环
DeQueue(Q,p);//队头结点出队
visit(p);//访问出队节点
if(p->lchild!=NULL)
EnQueue(Q,p->lchild);//左孩子入队
if(p->rchild!=NULL)
EnQueue(Q,p->rchild);//右孩子入队
}
}
//二叉树的存储链式存储
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
//链式队列结点
typedef struct BiTNode{
BiTNode *data;//存的是指针而不是结点
struct LinkNode *next;
}
typedef struct{
LinkNode *front,*next;//队头入队
}LinkQueue;
2.统计叶子节点个数
int NodeCount(BiTree T){
if(T==NULL) return ERROR;
else return NodeCount(T->lchild)+ NodeCount(T->rchild)+1;
}
//先序
int CountLeaf(BiTree T,int count)
{
if(T){
if ((T->lchild==NULL)&& (T->rchild==NULL))
count++; // 对叶子结点计数
count=CountLeaf( T->lchild,count;
count =CountLeaf( T->rchild,count);
}
} // CountLeaf
//后序
int CountLeaf(BiTree &T)
{ // int cright,cleft;
if (T==NULL)
return 0;
if ((T->lchild==NULL)&&(T->rchild==NULL))
return 1; // 对叶子结点计数
else
{
cleft=CountLeaf(T->lchild);
cright=CountLeaf(T->rchild);
return (cleft+cright);
}
return CountLeaf(T->lchild)+CountLeaf(T->rchild);
} // CountLeaf
3.后序遍历求解二叉树深度的算法
int Depth(BiTree T){
int m,n;
if(T==NULL) return ERROR;
else {
m=Depth(T->lchild);
n=Depth(T->rchild);
if(m>n) return (m+1);
else return(n+1);
}
}