采用dfs
/**
* 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) {//判断是不是平衡二叉树
if(root==null){return true;}
int l=dfs(root.left);
int r=dfs(root.right);
//平衡二叉树的条件,左右子树高度差小于等于1;左右子树都是平衡二叉树
if(Math.abs(r-l)<=1&&isBalanced(root.left)&&isBalanced(root.right)){return true;}
return false;
}
public int dfs(TreeNode root){//求子树的高度
if(root==null)return 0;
else return Math.max(dfs(root.left),dfs(root.right))+1;
}
}