思路:
1.平衡二叉树:左子树和右子树的高度相差不超过1
2.先计算当前左子树的高度和右子树的高度是否相差小于等于1,如果是那说明是平衡的,需要再进行判断当前左子树和右子树,他们的左右子树是否满足平衡条件,不断递归下去
3.递归条件isBanalced(root.left) && isBanalced(root.right) && [Math.abs(getHeight(root.right),getHeight(root.left)) <= 1]
public class Solution {
boolean isBanalced = true;
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true;
}
//getHeight(root);
//return isBanalced;
return isBanalced(root);
}
private boolean isBanalced(TreeNode root){
if(root == null){
return true;
}
int left = getHeight(root.left);
int right = getHeight(root.right);
if(Math.abs(right - left) > 1){
return false;
}
return isBanalced(root.left) && isBanalced(root.right);
}
private int getHeight(TreeNode node){
if(node == null){
return 0;
}
int left = getHeight(node.left);
int right = getHeight(node.right);
if(Math.abs(right - left) > 1){
isBanalced = false;
}
return Math.max(left, right)+1;
}
}