110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
判断一棵树是否平衡
因为平衡的定义就是左右子树的高度差不超过1 所以要求高度
很直接的想法就是从根节点到叶子节点 逐个求左右高度 然后判断是否是平衡的 

class solution {
public:
    int depth (TreeNode *root) {
        if (root == NULL) return 0;
        return max (depth(root -> left), depth (root -> right)) + 1;
    }

    bool isBalanced (TreeNode *root) {
        if (root == NULL) return true;
        
        int left=depth(root->left);
        int right=depth(root->right);
        
        return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
};

但是这个过程中有大量重复计算 比如输入是
        1
    2        3
4    5    6    7
在判断1是否平衡时 求2的高的同时 也求了4,5的高度 
但是之后判断2是否平衡 还会计算4,5的高度

所以要修改成先求叶子节点是否平衡 然后向上传递高度 所以需要设定一个返回值 同时包含子树是否平衡 又包含子树高度的信息
实际上 我们只需要能区分开平衡和高度就可以了 
int就够了 当不平衡时返回-1 高度是不可能为负数的 

    public boolean isBalanced(TreeNode root) {
        return getDepth(root) != -1;
    }
    
    private int getDepth(TreeNode root) {
        if (root == null) return 0;
        int left = getDepth(root.left);
        if (left == -1) return -1;
        int right = getDepth(root.right);
        if (right == -1) return -1;
        if (Math.abs(left-right) > 1) return -1;
        return Math.max(left, right) + 1;
    }

另外 getDepth可以写作
    private int getDepth(TreeNode root) {
        if (root == null) return 0;
        int left = getDepth(root.left);
        int right = getDepth(root.right);
        if (left == -1 || right == -1 || Math.abs(left-right) > 1) return -1;
        return Math.max(left, right) + 1;
    }


看上去会简洁一些 但实际上会增加计算量 比如 对于第一种写法 对于左子树不平衡的情况 是不需要求右子树的深度的
但是第二种写法 会求右子树的深度 所以第一种写法的效率高一些 相当于是失败快速返回的原则

直接写出了最优解 看了8个月之前的提交记录 提升不少 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值