题目描述:
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root)>=0;
}
int height(TreeNode root){//树的高度即树中所有结点深度的最大值
if(root==null){
return 0;
}
int left=height(root.left);
int right=height(root.right);
if(left>=0&&right>=0&&Math.abs(left-right)<=1){//判断符合平衡二叉树的条件,因为左右子树深度的绝对值的差大于一的话,就是不满足条件,直接返回-1上去,后面就不用再判断了(left>=0&&right>=0),一直返回-1到最顶层
return Math.max(left,right)+1;
}else{
return -1;
}
}
}