题目
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1 ,那么它就是一棵平衡二叉树。
代码
class Solution {
public boolean isBalanced ( TreeNode root) {
return pocess ( root) . isBalanced;
}
public class ReturnType {
public boolean isBalanced;
public int heigth;
public ReturnType ( boolean isBalanced, int heigth) {
this . isBalanced = isBalanced;
this . heigth = heigth;
}
}
public ReturnType pocess ( TreeNode node) {
if ( node == null) {
return new ReturnType ( true , 0 ) ;
}
ReturnType leftType = pocess ( node. left) ;
ReturnType rightType = pocess ( node. right) ;
int heigth = Math. max ( leftType. heigth, rightType. heigth) + 1 ;
boolean isBalanced = leftType. isBalanced && rightType. isBalanced
&& ( Math. abs ( leftType. heigth - rightType. heigth) <= 1 ) ;
return new ReturnType ( isBalanced, heigth) ;
}
}