核心代码:
int leaf(BiTreeNode *head)
{
if(head==NULL) return 0; //当前节点为空,返回0
else
{
if(head->LeftChild==NULL && head->RightChild==NULL) //当前节点的左右孩子节点为空,该节点为孩子节点,返回1
return 1;
else return leaf(head->RightChild)+leaf(head->LeftChild);//左右孩子有一个非空,那么递归求左右孩子的叶子节点,相加返回
}
}
全部代码:
#include<iostream>
#include<assert.h>
using namespace std;
typedef struct Lnode
{
char data;
struct Lnode *LeftChild;
struct Lnode *RightChild;
}BiTreeNode;
void Initiate(BiTreeNode **head)
{
(*head)=(BiTreeNode *)malloc(sizeof(BiTreeNode));
assert((*head)!=NULL); //if the judging conditio is true,this statement is not executed
(*head)->LeftChild=NULL;
(*head)->RightChild=NULL;
}
BiTreeNode * InsertLeftChild(BiTreeNode *head,char a )
{
if(head==NULL) return NULL;
BiTreeNode * p,*t;
t=head->LeftChild;
p=(BiTreeNode *)malloc(sizeof(BiTreeNode));
assert(p!=NULL);
p->data=a;
p->RightChild=NULL;
p->LeftChild=t;
head->LeftChild=p;
return head->LeftChild;
}
BiTreeNode *InsertRightChild(BiTreeNode *head,char a)
{
if(head==NULL) return NULL;
BiTreeNode *p,*t;
t=head->RightChild;
p=(BiTreeNode *)malloc(sizeof(BiTreeNode));
assert(p!=NULL);
p->data=a;
p->LeftChild=NULL;
p->RightChild=t;
head->RightChild=p;
return head->RightChild;
}
void Destroy(BiTreeNode *head)
{
if(head!=NULL && head->LeftChild!=NULL)
Destroy(head->LeftChild);
if(head!=NULL && head->RightChild!=NULL)
Destroy(head->RightChild);
free(head);
}
void LDR(BiTreeNode *head)
{
if(head!=NULL)
{
LDR(head->LeftChild);
cout<<head->data<<" ";
LDR(head->RightChild);
}
}
int leaf(BiTreeNode *head)
{
if(head==NULL) return 0;
else
{
if(head->LeftChild==NULL && head->RightChild==NULL)
return 1;
else return leaf(head->RightChild)+leaf(head->LeftChild);
}
}
void main()
{
BiTreeNode *head,*p,*q;
Initiate(&head);
head->data='g';
p=InsertLeftChild(head,'a');
p=InsertLeftChild(p,'b');
p=InsertRightChild(head,'c');
LDR(head);
cout<<endl;
cout<<"the leaf node:"<<leaf(head)<<endl;
Destroy(head);
system("pause");
}