Here is one way to check whether a binary tree is balanced:
Time complexity: O(n).
Space complexity: O(h) where h is height because of recursion and call stack requirements
checkBalancedTry in REPL1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| function checkHeight(root) { if (!root) return -1; const leftHeight = checkHeight(root.left); if (leftHeight === -Infinity) return -Infinity; const rightHeight = checkHeight(root.right); if (rightHeight === -Infinity) return -Infinity; const heightDiff = Math.abs(leftHeight - rightHeight); return heightDiff > 1 ? -Infinity : Math.max(leftHeight, rightHeight) + 1; } function checkBalanced(root) { return checkHeight(root) !== -Infinity; } function Tree(value) { this.value = value; this.left = null; this.right = null; }
|
Tests can be found at REPL.it