问题描述:
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
返回 true
。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1 / \ 2 2 / \ 3 3 / \ 4 4
返回 false
解题思路:解这种判断思路,没有好办法,就是按照定义去判断,所以算法中需要判断二叉树高度。
老规矩 先来自己的
扫描二维码关注公众号,回复:
3965083 查看本文章
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}else{
return (Math.abs(height(root.left)-height(root.right))<=1)&&isBalanced(root.left)&&isBalanced(root.right);
}
}
public int height(TreeNode root){
if(root == null){
return 0;
}else{
return 1+Math.max(height(root.left),height(root.right));
}
}
接下来,再来大神的,大神做的运行速度比我的快,递归写的很精妙,不容易一次写成,需要对题目理解很深才能写出,一般在毫无参考的时候不好直接想出来。
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
int height(TreeNode root)
{
if(root == null) return 0;
int left = height(root.left);
if(left == - 1) return -1;
int right = height(root.right);
if(right == -1) return -1;
if(Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
}