MEDIUM NC#56 Blind #68 Trees

98. Validate Binary Search Tree

๐Ÿ“– Problem

Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: - The left subtree of a node contains only nodes with keys less than the node's key. - The right subtree of a node contains only nodes with keys greater than the node's key. - Both the left and right subtrees must also be binary search trees.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขIn-place array updates
  • โ€ขSorted array traversal
  • โ€ขBoundary condition checks

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Two Pointers reasoning pattern
  • โ€ขApply Binary Search reasoning pattern
  • โ€ขApply DFS reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use DFS with min/max bounds for each node
  • โ†’ Initialize bounds as -Infinity and Infinity
  • โ†’ Left child must be < current node, right child must be > current node
  • โ†’ Time: O(n), Space: O(h) where h is tree height

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse DFS with min/max bounds for each node
  • โ€ขInitialize bounds as -Infinity and Infinity
  • โ€ขLeft child must be < current node, right child must be > current node

Common Pitfalls

  • โ€ขTime: O(n), Space: O(h) where h is tree height

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
validate(node: TreeNode | null, min: number, max: number);
Expected:
Computed from hidden reference
Test Case 2
Not run
Input:
validate(node.left, min, node.val);
Expected:
Computed from hidden reference
Test Case 3
Not run
Input:
validate(node.right, node.val, max);
Expected:
Computed from hidden reference

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit