您的位置:首页 > 其它

判断是否为平衡二叉树--递归法

2016-03-13 21:19 281 查看


求树的深度

用递归做很简单,只要知道递归出口语句的别写错。

[cpp] view
plaincopy

struct BinaryTreeNode  

{  

    int m_Value;  

    BinaryTreeNode* m_pLeft;  

    BinaryTreeNode* m_pRight;  

};  

  

int TreeDepth(BinaryTreeNode* pRoot)  

{  

    if (pRoot == NULL)  

        return 0;  

  

    int nLeftDepth = TreeDepth(pRoot->m_pLeft);  

    int nRightDepth = TreeDepth(pRoot->m_pRight);  

  

    return (nLeftDepth>nRightDepth)?(nLeftDepth+1):(nRightDepth+1);  

}  


判断该树是否为平衡二叉树

调用上述函数求每个节点的左右孩子深度

[cpp] view
plaincopy

bool IsBalanced(BinaryTreeNode* pRoot)  

{  

    if(pRoot== NULL)  

        return true;  

  

    int nLeftDepth = TreeDepth(pRoot->m_pLeft);  

    int nRightDepth = TreeDepth(pRoot->m_pRight);  

    int diff = nRightDepth-nLeftDepth;  

  

    if (diff>1 || diff<-1)  

        return false;  

  

    return IsBalanced(pRoot->m_pLeft)&&IsBalanced(pRoot->m_pRight);  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: