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 Tree INPUT Binary Tree Structure 2 1 3 Left < Root Right > Root root = [2, 1, 3] Array representation Root: 2, Left: 1, Right: 3 Check: 1 < 2 < 3 ALGORITHM STEPS Inorder Traversal 1 Start Inorder Go left, visit, go right 2 Visit Node 1 First node, prev = null 3 Visit Node 2 Check: 2 > 1 (OK) 4 Visit Node 3 Check: 3 > 2 (OK) Inorder Sequence: 1 < 2 < 3 Sorted = Valid BST FINAL RESULT Valid BST Confirmed 2 1 3 OK OK OK Output: true All conditions met: 1 < 2 (left < root) 3 > 2 (right > root) Both subtrees valid Key Insight: Inorder traversal of a valid BST produces a strictly increasing sequence. By comparing each node with the previous visited node, we can validate the BST property in O(n) time complexity with O(h) space for the recursion stack (h = tree height). TutorialsPoint - Validate Binary Search Tree | Inorder Traversal Approach
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