求二叉树的叶子结点个数
分析
这个题目很简单,我想到了两个思路
- 1、跑一遍二叉树的先序遍历,每个结点判断是否有左孩子和右孩子,若都没有Count+1
- 2、利用递归的思想,每个结点都进行同样的判断:判断是否有左孩子或右孩子,若都没有Count+1,若有则针对左右孩子递归调用
1的代码段
#define MAX_NODE 50;
int SearchLeavesNode(BTNode *T){
BTNode *stack[MAX_NODE],*p=T,*q;
int top=0,Count=0;
if(T==NULL){
printf("Empty");
}
else{
do{
if(p->Lchild==NULL&&p->Rchild==NULL)
Count++;
//下是先序遍历
q=p->Rchild;
if(q!=null){
//入栈
stack[++top]=q;
}
p=p->Lchild;
if(p==NULL){
//弹栈
p=stack[top];
top--;
}
}while(p!=NULL);
}
return Count;
}
2的代码段
int SearchLeavesNode(BTNode *T,Count){
if(T!=NULL){
if(T->Lchild==NULL&&T->Rchild==NULL){
Count++;
Count=SearchLeavesNode(T->Lchild,Count);
Count=SearchLeavesNode(T->Rchild,Count);
}