Balanced Binary Tree Visualizer & Step-by-Step Algorithm Solution

Determine if a binary tree is height-balanced (depth of the two subtrees of every node never differs by more than 1).

Category: trees | Difficulty: Easy

Tags: DFS, Binary Tree, Recursion, Tree Height, Tree Property

Balanced Binary Tree

3
9
20
15
7
100%
state
balancedtrue
Initialization
1/28
Explanation

Start isBalanced on binary tree with root: Node(3).

Source Code
1function isBalanced(root) {
2 let balanced = true;
3 function height(node) {
4 if (!node) return 0;
5 const left = height(node.left);
6 const right = height(node.right);
7 if (Math.abs(left - right) > 1) balanced = false;
8 return 1 + Math.max(left, right);
9 }
10 height(root);
11 return balanced;
12}