31 - 平衡二叉树
Last updated
Last updated
var isBalanced = function (root) {
return depth(root) !== -1;
};
const depth = function (root) {
if (!root) {
return 0
}
let left = depth(root.left);
if (left === -1) {
return -1
}
let right = depth(root.right);
if (right === -1) {
return -1
}
return Math.abs(left - right) < 2 ? Math.max(left, right) + 1: -1
}var height = function (node) {
if (!node) {
return 0
}
return 1 + Math.max(height(node.right), height(node.left))
}
var isBalanced = function (root) {
if (!root) {
return true
}
return Math.abs(height(root.right) - height(root.left)) < 2 && isBalanced(root.left) && isBalanced(root.right)
}