Skip to content
DSA Patterns
Menu
Language
Tree DFSLC #981 of 6Next →

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

Mediumtree-dfs

Validate Binary Search Tree

Problem (restated)

Determine whether a binary tree is a valid BST: every node is strictly greater than all in its left subtree and strictly less than all in its right.

Intuition

Pass (low, high) down each edge. Node value must lie inside the open interval.

Approaches

Bounds DFS

Unverified
Time O(n)Space O(h)

Idea. isValid(node, low, high): null ok; low < val < high; recurse left (low,val) and right (val,high).

Walkthrough. Invalid classic: root 5, right 4 (4 is not > 5).

Trade-offs. Bounds DFS is clean; inorder must be strictly increasing.

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 isValidBST(root: TreeNode | null): boolean {
  const go = (node: TreeNode | null, low: number, high: number): boolean => {
    if (!node) return true;
    if (node.val <= low || node.val >= high) return false;
    return go(node.left, low, node.val) && go(node.right, node.val, high);
  };
  return go(root, -Infinity, Infinity);
}
export function isValidBST(root: TreeNode | null): boolean {
  const go = (node: TreeNode | null, low: number, high: number): boolean => {
    if (!node) return true;
    if (node.val <= low || node.val >= high) return false;
    return go(node.left, low, node.val) && go(node.right, node.val, high);
  };
  return go(root, -Infinity, Infinity);
}

Template connection

Bounds travel downward. isValid(node, low, high) accepts null, requires low < val < high, then calls the left child with (low, val) and the right with (val, high).

Reflection

  • Checking the parent is not enough. A value deep on the right can still be smaller than the root. The open range (low, high) is what travels down.
  • An equal child is not a BST. For a value at the integer limit, leave the bound null. Do not use MinValue as if it were a real limit.
  • One node is true. An empty tree is true.
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 4
1/4

Validate BST on a real tree. Pass (low, high) bounds down each edge.

5(-∞,∞)1436

low < val < high

Key:CurrentActive rangeMatchSettledEliminated