輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹

    int TreeDepth(TreeNode* pRoot)
{
     if(!pRoot)
           return 0;

     int nLeft = TreeDepth(pRoot->left);
     int nRight = TreeDepth(pRoot->right);

     return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}
class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if (pRoot == NULL)
            return true;
        int nleft = TreeDepth(pRoot->left);
        int nright = TreeDepth(pRoot->right);
        if ((nleft - nright) > 1 || (nright -nleft) > 1 )
            {
                return false;
            }
        return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
    }
};
發佈了40 篇原創文章 · 獲贊 12 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章