可以使用求树的深度的方法,求出每一个叶节点的深度,进行比较。也可以递归,从底到根看左右节点是不是平衡,如果平衡,那么就返回下面有几层。如果不平衡就返回-1,方法中左右节点获得的返回值如果是-1,就说明存在不平衡的情况,不需要往下执行。直接返回-1即可。最终方法得到的值如果是-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;
}
int count=getDeep(root);
return count!=-1;
}
public int getDeep(TreeNode node){
int ll=0;
int rr=0;
if(node.left!=null){
ll= getDeep(node.left);
}
if(ll==-1){
return -1;
}
if(node.right!=null){
rr=getDeep(node.right);
}
if(rr==-1){
return -1;
}
if(ll-rr>1 || ll-rr<-1){
return -1;
}
int max = ll<rr? rr:ll;
return max+1;
}
}