获取二叉树的结点,叶子节点,层数,以及k层结点个数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Wan_shibugong/article/details/80220533

二叉树的拷贝
二叉树结点的个数(递归)

int BinTreeSize(pBTNode pRoot)
{
    if(NULL == pRoot)
        return 0;
    return BinTreeSize(pRoot->_pLeft)+BinTreeSize(pRoot->_pRight)+1;
#if 0
    int leftsize = 0;
    int rightsize = 0;
    if(NULL == pRoot)
        return 0;
    leftsize = BinTreeSize(pRoot->_pLeft);    //左子树的节点数
    rightsize = BinTreeSize(pRoot->_pRight);  //右子树的节点数
    return leftsize+rightsize+1;            
#endif

}

二叉树叶子结点的个数
思路
空树->0 返回0
只有根节点->1 返回1
二叉树 返回left+right

int GetLeafCount(pBTNode pRoot) 
{
    if(NULL == pRoot)
        return 0;

     //如果该节点是根节点返回1
    if(NULL == pRoot->_pLeft && NULL == pRoot->_pRight) 
            return 1;
    //不是根节点返回左子树+右子树
    return GetLeafCount(pRoot->_pLeft)+GetLeafCount(pRoot->_pRight);
}

二叉树的层数
步骤
如果空树 为零
如果不为空 第一层为1
求第K层 可以先求一左树的k-1层+右树的k-1层
直到每次执行到一个根的 第一层返回1, 如果没有的话返回0

int Height(pBTNode pRoot)
{
    int leftHeight = 0;
    int rightHeight = 0;
    if(NULL == pRoot)
        return 0;
    leftHeight = Height(pRoot->_pLeft);
    rightHeight = Height(pRoot->_pRight);

    return leftHeight > rightHeight ? leftHeight+1 : rightHeight+1;
}

二叉树第K层的结点的个数
求二叉树的高度
步骤
空树 返回0
只有根节点 返回1
二叉树返回 left>right?left+1:right+1

int GetKLevelNode(pBTNode pRoot, int K)
{
    if(NULL == pRoot || K<=0)
        return 0;
    if(K == 1)
        return 1;
    return GetKLevelNode(pRoot->_pLeft,K-1)+GetKLevelNode(pRoot->_pRight,K-1);
}

猜你喜欢

转载自blog.csdn.net/Wan_shibugong/article/details/80220533