题目描述:给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
解法一
自顶向下遍历检查
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution{
public boolean isBalanced(TreeNode root)
{
if(root==null)
return true;
else
{
if(Math.abs(height(root.left)-height(root.right))<=1&&isBalanced(root.left)&&isBalanced(root.right))
return true;
else
return false;
}
}
public int height(TreeNode root)
{
if(root==null)
return 0;
else
return Math.max(height(root.left),height(root.right))+1;
}
}
解法二
自下至顶遍历检查
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null)
return true;
else
return height(root)>0;
}
public int height(TreeNode root)
{
if(root==null)
return 0;
else
{
int leftheight=height(root.left);
int rightheight=height(root.right);
if(leftheight==-1||rightheight==-1||Math.abs(leftheight-rightheight)>1)
return -1;
else
return Math.max(leftheight,rightheight)+1;
}
}
}