输入一棵二叉树,判断该二叉树是否是平衡二叉树。
如果一棵树是平衡二叉树则返回该树的高度,否则返回-1
对于一棵树只要判断其左右子树均为平衡二叉树且高度相差不超过1则为平衡二叉树
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
int h = getDepth(root);
boolean res = h == -1 ? false : true ;
return res;
}
private int getDepth(TreeNode root){
if( root == null) return 0;
int left = getDepth(root.left);
if(left == -1) return -1;
int right = getDepth(root.right);
if(right == -1 || Math.abs(left-right) > 1)
return -1;
else return Math.max(left, right) + 1;
}
}