题目
题解
K神大佬详细题解:面试题55 - II. 平衡二叉树(从底至顶、从顶至底,清晰图解)
解法一:先序遍历
计算左右子树最大深度、然后递归判断是否子树大于1,大于1就不是平衡二叉树。
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null){
return true;
}
return Math.abs(depth(root.left)-depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
private int depth(TreeNode root){
if (root == null){
return 0;
}
return Math.max(depth(root.left),depth(root.right)) + 1;
}
}