leetcode(30).110. Balanced Binary Tree

题意:判断给定的二叉树是否是平衡树。(平衡树是指树的子树结点高度差不超过一)

初步分析:

深度考虑深度优先搜索,采用递归的方式实现。再比较判断高度差是否超过1.

我们可以把递归的部分设置为高度

然后,现在我们可以获得子树的高度了,那么左子树和右子树的高度差不能超过1。

然而,仅仅这样是错的。

比如

         *

      *     *

   *         *

 *

根节点的左子树和右子树虽然只差了1.,但是对于左子树

     *

  *

*

显然是不平衡的。

所以,判断平衡也是递归的,不仅自己要平衡,还要递归的判断左子树和右子树也是平衡的。

public class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) 
              return true;
        return (Math.abs(getHeight(root.left) - getHeight(root.right)) < 2) 
                  && isBalanced(root.left)
                  && isBalanced(root.right);
    }
    
    public int getHeight(TreeNode root) {  
        if (root == null)
            return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}

把非递归判断和递归分开也不无不可

public class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) 
              return true;
        if(Math.abs(getHeight(root.left) - getHeight(root.right)) > 1)
            return false;
        return isBalanced(root.left) && isBalanced(root.right);
    }
    
    public int getHeight(TreeNode root) {  
        if (root == null)
            return 0;
        return 1 + Math.max(getHeight(root.left), getHeight(root.right));
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值