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;
}
}
嗯。。先贴着,,改天再研究吧。。