Open zentan66 opened 3 years ago
var isBalanced = function (root) {
function height(root) {
if (!root) {
return 0
}
let leftHeight = height(root.left)
let rightHeight = height(root.right)
if (
leftHeight === -1 ||
rightHeight === -1 ||
Math.abs(leftHeight - rightHeight) > 1
) {
return -1
}
return Math.max(leftHeight, rightHeight) + 1
}
return height(root) >= 0
}
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1