Skip to content
ΣDSA Patterns
Menu
Language

Tree DFS

Guide 4 of 6 · Path 4 of 6

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
3920157

post-order: children first, then me

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

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

Tested only
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
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 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;
}

Template connection

Tree DFS multi-field return.

Reflection