1、设计算法求二叉树的结点个数。
void Count(BiNode *root){
if (root) {
Count(root->lchild);
number+ +; //number为数据成员
Count(root->rchild);
}
}
2、树中节点的数目
左子树中节点的数目+右子树中节点的数目+1
template<class T>
int BiTree<T>::count(BiNode<T>* root){
int number=0;
if (root==NULL)
number=0;
else
number=count(root->lchild)+count(root->rchild)+1;
return number;
}
3、统计叶子节点的数目
增加一个数据成员,leafcount, 初值为0
对树进行遍历。 如果一个节点是叶子,则将leafcount+1;
可以在前序、中序或后序的遍历过程中进行计算。
template<typename T>
void BiTree<T>:: countleaf(BiTreeNode<T> * root){
if (root) {
if (root->lchild==NULL && root->rchild==NULL)
leafcount=leafcount+1;
else
{
countleaf(root->lchild);
countleaf(root-