题目描述:求二叉树叶子结点个数。
分析: 考虑递归和非递归两种方法
<1>递归
int Leaves(BiTree T){
if(T == NULL)
return 0;
if(T->lchild == NULL && T->rchild == NULL)
return 1;
else
return Leaves(T->lchild) + Leaves(T->rchild);
}
<2>非递归
思路: 非递归可以使用队列实现
int Leaves2(BiTree T){
InitQueue(Q);
BiTNode *p;
EnQueue(Q,T);
int count = 0;
while(!IsEmpty(Q)){
DeQueue(Q,p);
if(p->lchild == NULL && p->rchild == NULL)
count++;
if(p->lchild)
EnQueue(Q,p->lchild);
if(p->rchild)
EnQueue(Q,p->rchild);
}
return count;
}
题目描述:求二叉树非叶子结点个数。
分析: 两种方法,递归与非递归
<1>递归
int NoLeaves(BiTree T){
if(T == NULL)
return 0;
if(T->lchild == NULL && T->rchild == NULL)
return 0;
else
return NoLeaves(T->lchild) + NoLeaves(T->rchild) + 1;
}
<2>非递归
int NoLeaves2(BiTree T){
InitQueue(Q);
BiTNode *p;
EnQueue(Q,T);
int count = 0;
while(!IsEmpty(Q)){
DeQueue(Q,p);
if(p->lchild == NULL && p->rchild == NULL)
count = count;
else
count++;
if(p->lchild)
EnQueue(Q,p->lchild);
if(p->rchild)
EnQueue(Q,p->rchild);
}
return count;
}