实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
if(Math.abs(depth(root.left)-depth(root.right))>1){//判断当前结点的左右子树
return false;
}else{//递归遍历左右节点
return isBalanced(root.left) && isBalanced(root.right);
}
}
//判断树的最大深度
public int depth(Tree root){
if(root == null) return 0;
return Math.max(depth(root.left),depth(root.right))+1;
}
}