LeetCode 110 check if balanced binary tree
平衡树的定义:
任意节点的左右子节点的高度差不超过1.
说到左右子树 就想到递归。
我们要check所有的节点是不是符合这个要求。
isBalanced(root) = isBalanced(root.left) && isBalanced(root.right)
but given a node, how to check if it is or not, we should do this:
isBalanced(root) = Math.abs(height(root.left) - height(root.right)) < 1
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
if (Math.abs(height(root.left) - height(root.right)) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode root) {
if (root == null) return 0;
return Math.max(height(root.left), height(root.right)) + 1;
}
}
the first time i wrote this code,
if (Math.abs(height(root.left) - height(root.right)) <= 1) {
return true;
}
这样是不对的 因为我们只能判断什么时候一定false 因为就算当前满足了这个条件 仍然是需要往下来看。

浙公网安备 33010602011771号