72. 平衡二叉树

class Solution {
public:
    bool ans = true;;
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        maxDepth(root);
        return ans;
    }
    
    int maxDepth(TreeNode* root)
    {
        if(root == NULL) return 0;
        //root的左、右子树的最大深度
        int leftDepth = maxDepth(root->left);
        int rightDepth = maxDepth(root->right);
        if(abs(leftDepth-rightDepth) > 1){
            ans =false;
        }
        //else ans=true;添加这行代码就会报错
       
        //返回的是左右子树的最大深度+1
        return max(leftDepth, rightDepth) + 1;
    }
};

上面的代码添加一行后报错,如下代码解释了为什么

 class Solution {
 public:
    #计算树的深度
    int treeDepth(TreeNode* root){
        if(!root) return 0;
        return max(treeDepth(root->left),treeDepth(root->right))+1;
    }
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        int left = treeDepth(root->left);
        int right = treeDepth(root->right);
        #判断左右子树是否满足条件,然后如果满足条件,判断子树的子树是否满足条件
        if(abs(left-right)<=1) return isBalanced(root->left)&&isBalanced(root->right);

        #如果不满足条件直接返回false
        else return false;
    }
};

作者:蜗牛壳
链接:https://www.acwing.com/solution/acwing/content/1779/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自www.cnblogs.com/make-big-money/p/12338774.html