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
๐งญ Prerequisites
๐ ๏ธ 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
๐ค Output