0
0
DSA Javascriptprogramming

Check if Binary Tree is Balanced in DSA Javascript

Choose your learning style9 modes available
Mental Model
A binary tree is balanced if for every node, the height difference between its left and right subtrees is at most one.
Analogy: Imagine a tree with branches on both sides. If one side is much taller than the other, the tree might lean or fall. A balanced tree stands straight because both sides grow evenly.
      1
     / \
    2   3
   /     \
  4       5
Dry Run Walkthrough
Input: Binary tree: 1 with left child 2, right child 3; 2 has left child 4; 3 has right child 5
Goal: Determine if the tree is balanced by checking height differences at each node
Step 1: Check leaf node 4: left and right heights are 0
Node 4: height=1, balanced=true
Why: Leaf nodes have height 1 and are balanced by definition
Step 2: Check node 2: left height=1 (from 4), right height=0 (no child)
Node 2: height=2, balanced=true (difference 1)
Why: Height difference is 1, so node 2 is balanced
Step 3: Check leaf node 5: left and right heights are 0
Node 5: height=1, balanced=true
Why: Leaf nodes have height 1 and are balanced
Step 4: Check node 3: left height=0, right height=1 (from 5)
Node 3: height=2, balanced=true (difference 1)
Why: Height difference is 1, so node 3 is balanced
Step 5: Check root node 1: left height=2 (from 2), right height=2 (from 3)
Node 1: height=3, balanced=true (difference 0)
Why: Height difference is 0, so root is balanced
Result:
1 (height=3, balanced) -> 2 (height=2, balanced) -> 3 (height=2, balanced) -> 4 (height=1, balanced) -> 5 (height=1, balanced)
Final answer: Tree is balanced
Annotated Code
DSA Javascript
class TreeNode {
  constructor(val = 0, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function isBalanced(root) {
  // Returns [height, balanced] for subtree rooted at node
  function check(node) {
    if (node === null) return [0, true];

    const [leftHeight, leftBalanced] = check(node.left); // check left subtree
    const [rightHeight, rightBalanced] = check(node.right); // check right subtree

    const height = Math.max(leftHeight, rightHeight) + 1; // current node height
    const balanced = leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) <= 1; // balanced if subtrees balanced and height diff <=1

    return [height, balanced];
  }

  return check(root)[1];
}

// Driver code using dry_run input
const root = new TreeNode(1,
  new TreeNode(2, new TreeNode(4), null),
  new TreeNode(3, null, new TreeNode(5))
);

console.log(isBalanced(root) ? "Tree is balanced" : "Tree is not balanced");
if (node === null) return [0, true];
base case: empty subtree has height 0 and is balanced
const [leftHeight, leftBalanced] = check(node.left);
recursively check left subtree height and balance
const [rightHeight, rightBalanced] = check(node.right);
recursively check right subtree height and balance
const height = Math.max(leftHeight, rightHeight) + 1;
calculate current node height as max of children plus one
const balanced = leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) <= 1;
node is balanced if both subtrees balanced and height difference ≤ 1
return [height, balanced];
return height and balance status up the recursion
return check(root)[1];
final answer is balance status of entire tree
OutputSuccess
Tree is balanced
Complexity Analysis
Time: O(n) because we visit each node once to compute heights and check balance
Space: O(h) where h is tree height due to recursion stack
vs Alternative: Naive approach checks height separately for each node causing O(n^2) time; this method combines height and balance check in one pass for O(n) time
Edge Cases
Empty tree (root is null)
Returns true because empty tree is balanced
DSA Javascript
if (node === null) return [0, true];
Single node tree
Returns true because single node is balanced
DSA Javascript
if (node === null) return [0, true];
Tree with one side deeper by more than 1
Returns false because height difference > 1 at some node
DSA Javascript
const balanced = leftBalanced && rightBalanced && Math.abs(leftHeight - rightHeight) <= 1;
When to Use This Pattern
When a problem asks if a tree is balanced or height differences matter, use a bottom-up recursion that returns height and balance status together to avoid repeated height calculations.
Common Mistakes
Mistake: Calculating height separately for each node causing repeated work and O(n^2) time
Fix: Combine height and balance check in one recursive function returning both values
Mistake: Checking balance only at root and ignoring subtrees
Fix: Check balance at every node by combining subtree results
Summary
Checks if a binary tree is balanced by ensuring height difference between left and right subtrees is at most one at every node.
Use when you need to verify tree balance efficiently without repeated height calculations.
The key insight is to return height and balance status together from each subtree in one recursion.