文章出處

題目描述
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。

考察平衡樹的概念和遞歸的使用。平衡樹是指,樹中的每個節點的左右子樹的高度差小于等于1。

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot == NULL){
            return true;
        }
        if(IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right)){
            int left_depth = getDepth(pRoot->left);
            int right_depth = getDepth(pRoot->right);
            if(abs(left_depth-right_depth)<=1){
                return true;
            }
            return false;
        }
        return false;
    }
    int getDepth(TreeNode* pRoot){
        if(pRoot == NULL){
            return 0;
        }
        return 1+max(getDepth(pRoot->left), getDepth(pRoot->right));
    }
};

文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()