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 strictly less than the node's key.
  • The right subtree of a node contains only nodes with keys strictly greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Input & Output

Example 1 — Valid BST
$ Input: root = [2,1,3]
Output: true
💡 Note: The tree is a valid BST: left child 1 < root 2 < right child 3, and all subtrees are valid BSTs
Example 2 — Invalid BST
$ Input: root = [5,1,4,null,null,3,6]
Output: false
💡 Note: The right subtree contains 3 which is less than root 5, violating BST property
Example 3 — Single Node
$ Input: root = [1]
Output: true
💡 Note: A single node is always a valid BST

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -231 ≤ Node.val ≤ 231 - 1

Visualization

Tap to expand
Validate Binary Search TreeValid BSTInvalid BST5383 < 5 ✓8 > 5 ✓51431 < 5 ✓4 < 5 ✗3 < 5 ✗BST Property: For every node, all left descendants < node < all right descendantsLeft tree: All nodes satisfy property → Valid Right tree: Node 3 violates property → Invalid
Understanding the Visualization
1
Input Tree
Binary tree with nodes and values
2
BST Rules
Left < Root < Right for all nodes
3
Validation
Check if all nodes follow BST property
Key Takeaway
🎯 Key Insight: Use min/max bounds to validate each node's position relative to its ancestors
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
67.8K Views
High Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen