题目描述
题目链接110. 平衡二叉树
题解
自顶向下(暴力):
- 求左子树的深度,右子树的深度,两个深度相减,如果绝对值小于1,递归判断左子树,右子树
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
int left = getDepth(root.left);
int right = getDepth(root.right);
if (Math.abs(left - right) > 1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
public int getDepth(TreeNode root){
if (root == null) return 0;
int left = getDepth(root.left);
int right = getDepth(root.right);
return Math.max(left, right) + 1;
}
}
自底向上:
- 在求树的高度的同时,验证每个节点是否是平衡二叉树
- 递归到最下层的时候,求左子树的深度left,右子树的深度right
- 如果
Math.abs(left - right < 1)
,则返回当前子树的深度,供上层计算。 否则返回 -1,表示当前节点不是平衡二叉树。上层也就不用继续计算了,直接返回 -1. - 最后看递归函数返回的是否是-1
class Solution {
public boolean isBalanced(TreeNode root) {
return check(root) != -1;
}
public int check(TreeNode root){
if (root == null) return 0;
int left = check(root.left);
if (left == -1) return -1;
int right = check(root.right);
if (right == -1) return - 1;
if (Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
}