Balanced Binary Tree
Description
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3 / \ 9 20 / \ 15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1 / \ 2 2 / \ 3 3 / \ 4 4
Return false.
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
const isBalanced = (root) => {
const height = (node, currentHeight) => {
if (!node) {
return currentHeight
}
let leftHeight = currentHeight
let rightHeight = currentHeight
if (node.left) {
leftHeight = height(node.left, currentHeight + 1)
}
if (node.right) {
rightHeight = height(node.right, currentHeight + 1)
}
return leftHeight > rightHeight ? leftHeight : rightHeight
}
if (!root) {
return true
}
const leftHeight = root.left ? height(root.left, 1) : 0
const rightHeight = root.right ? height(root.right, 1) : 0
if (
(Math.abs(leftHeight - rightHeight) <= 1) && isBalanced(root.left) && isBalanced(root.right)
) {
return true
}
return false
}