求二叉树中叶子节点个数,总的节点个数

struct BinaryTree  
{  
    char value;  
    BinaryTree* left;  
    BinaryTree* right;  
};  
  
//求二叉树中的节点个数  
//(1)如果二叉树为空,节点个数为0  
//(2)如果二叉树不为空,二叉树节点个数 = 左子树节点个数 + 右子树节点个数 + 1  
int getNodeNums(BinaryTree* pRoot)  
{  
    if(pRoot==NULL)  
        return 0;  
    return getNodeNums(pRoot->left)+getNodeNums(pRoot->right)+1;  
}  
  
//求二叉树中叶子节点的个数  
//(1)如果二叉树为空,返回0  
//(2)如果二叉树不为空且左右子树为空,返回1  
//(3)如果二叉树不为空,且左右子树不同时为空,返回左子树中叶子节点个数加上右子树中叶子节点个数  
int getLeafNodeNums(BinaryTree* pRoot)  
{  
    if(pRoot==NULL)  
        return 0;  
    if(pRoot->left==NULL && pRoot->right==NULL)  
        return 1;  
    int leftNums = getLeafNodeNums(pRoot->left);  
    int rightNums = getLeafNodeNums(pRoot->right);  
    return leftNums+rightNums;  
}  

猜你喜欢

转载自hulefei29.iteye.com/blog/1997090