择天记教宗真正身份:写一个算法来计算给定二叉树的叶结点数

来源:百度文库 编辑:中科新闻网 时间:2024/04/30 01:58:48
用C语言编写

用递归函数,算法如下:
int leafs(BTree *b)
{int num1,num2;
if (b==NULL)
return(0);
else if
(b->left=NULL&&b->right=NULL)
return(1);
else {
num1=leafs(b->left);
num2=leafs(b->right);
return(num1+num2);
}
}

编程:
link creat_btree(link btree)
{char _data;
link newnode;
link back=btree;
link first=btree;
cout<<"input the information of the new node :";
cin>>_data;
newnode=new(BT);
newnode->data=_data;
newnode->right=NULL;
newnode->left=NULL;
if(btree==NULL)
{
btree=newnode;
return btree;
}
else
{
while(first!=NULL)
{back=first;
if((newnode->data)>(first->data))
first=first->right;
else
first=first->left;
}
}
if((newnode->data)>(back->data))
back->right=newnode;
else back->left=newnode;
return btree;
}