1 | 给定一个二叉树,判断它是否是高度平衡的二叉树。 |
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null)
return true;
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;
return Math.max(root.left==null?0:height(root.left), root.right==null?0:height(root.right))+1;
}
}
1 | **方式二:** |
public boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
public int height(TreeNode root) {
if (root == null) {
return 0;
}
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;
}
}