Skip to content
DSA Patterns
Menu
Language
Tree DFSLC #1104 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Balanced Binary Tree

Problem (restated)

A height-balanced tree has |leftHeight, rightHeight| ≤ 1 at every node. Check if the tree is balanced.

Intuition

Return height from each subtree; if either side is unbalanced or heights differ by >1, bubble a sentinel.

Approaches

Height + flag DFS

Unverified
Time O(n)Space O(h)

Idea. height(node): if either child returns -1 or |hl-hr|>1 return -1; else 1+max.

Walkthrough. Perfect small trees ok; a long chain on one side fails.

Trade-offs. Single DFS O(n) vs naive recompute height O(n²).

Solution
Show helper code
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
export function isBalanced(root: TreeNode | null): boolean {
  const height = (node: TreeNode | null): number => {
    if (!node) return 0;
    const hl = height(node.left);
    if (hl < 0) return -1;
    const hr = height(node.right);
    if (hr < 0) return -1;
    if (Math.abs(hl - hr) > 1) return -1;
    return 1 + Math.max(hl, hr);
  };
  return height(root) >= 0;
}
export function isBalanced(root: TreeNode | null): boolean {
  const height = (node: TreeNode | null): number => {
    if (!node) return 0;
    const hl = height(node.left);
    if (hl < 0) return -1;
    const hr = height(node.right);
    if (hr < 0) return -1;
    if (Math.abs(hl - hr) > 1) return -1;
    return 1 + Math.max(hl, hr);
  };
  return height(root) >= 0;
}

Template connection

Null returns height 0. A child height of −1, or |hl - hr| > 1, returns −1. Otherwise the height is 1 + max(hl, hr). isBalanced is height(root) >= 0. The flag rides inside the height, so one walk returns both.

Reflection

  • Every node needs its two heights to differ by at most 1. The root can look fine while a subtree is not. Send that fact up with the height.
  • An unbalanced subtree can return −1 and skip the sibling. A leaf is balanced.
  • A long chain with a single child is unbalanced. An empty tree is balanced.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 8
1/8

Tree DFS walks structure, not a flat list. Root 3, left 9, right subtree 20 → 15, 7.

3920157
Statenode=3order=post-order

post-order: children first, then me

Key:CurrentActive rangeMatchSettled