题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true;
}
return IsBalanced_Solution_Core(root).isBalance;
}
public returnType IsBalanced_Solution_Core(TreeNode root){
if(root == null){
return new returnType(true,0);
}
returnType left = IsBalanced_Solution_Core(root.left);
returnType right = IsBalanced_Solution_Core(root.right);
if(left.isBalance == false ||right.isBalance == false ){
return new returnType(false,0);
}else if(Math.abs(left.length-right.length)>1){
return new returnType(false,0);
}
int length = left.length>right.length?left.length+1:right.length+1;
return new returnType(true,length);
}
public class returnType{
boolean isBalance;
int length;
public returnType(boolean isBalance,int length){
this.isBalance = isBalance;
this.length = length;
}
}
}
定义一个类,返回每次需要的信息
- 当前是否是平衡二叉树
- 当前深度
每个节点需考虑
- 左子树 或 右子树不是平衡,则父节点不可能平衡
- 左子树 - 右子树的差大于1,则父节点不可能平衡
- 如果不平衡,关键是返回false,深度传0即可
Math.abs();
差要取绝对值