Write an algorithm that determines if a binary tree is balanced or not. A balanced binary tree is defined as one where for every node, its left and right subtrees differ in height by no more than 1.
Utilisateur anonyme
class TreeNode { constructor(val, left = null, right = null) { this.val = val; this.left = left; this.right = right; } } function isBalanced(root) { function check(node) { if (node === null) { return { height: 0, balanced: true }; } const left = check(node.left); const right = check(node.right); const height = 1 + Math.max(left.height, right.height); const balanced = left.balanced && right.balanced && Math.abs(left.height - right.height) <= 1; return { height, balanced }; } return check(root).balanced; }