leetcode110_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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

 

首先要清楚平衡二叉树的概念:

1.根节点为空或者左右子树深度差不大于1(即小于等于1)

2.左右子树也是平衡二叉树

 

所以解决的思路是:

首先判断是否为空树,然后判断是否两边深度差不大于1,然后满足不大于1的再去递归判断是否左右子树也都是平衡二叉树。其中要写一个深度判断的子函数。具体代码如下:

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null){return true;}
        if(Math.abs(treeDepth(root.left)-treeDepth(root.right))>1){return false;}//注意数学函数Math首字母大写abs小写
        else if(isBalanced(root.left)&&isBalanced(root.right)){return true;}
        else{return false;}
    }
    public int treeDepth(TreeNode root){
        if(root==null){return 0;}
        return(1+Math.max(treeDepth(root.left),treeDepth(root.right)));
    }
}

以上代码运行时间2ms,贴一个运行时间1ms的代码:

class Solution {
    public boolean isBalanced(TreeNode root) {
        int res=isBal(root);
        return res!=-1;
    }
    private int isBal(TreeNode root){
        if(root==null)  return 0;
        int l=isBal(root.left);
        if(l==-1)   return l;
        int r=isBal(root.right);
        if(r==-1)   return r;
        if(Math.abs(l-r)<2) return 1+Math.max(l,r);
        return -1;
    }
}

嗯。。先贴着,,改天再研究吧。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值