Skip to content

Validate Binary Search Tree

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree contains only nodes with keys greater than the node’s key.
  • Both left and right subtrees must also be binary search trees.
InputOutputExplanation
[2,1,3]true1 < 2 < 3 ✓
[5,1,4,null,null,3,6]falseNode 4 should be > 5
  • The number of nodes is in range [1, 10^4].
  • -2^31 <= Node.val <= 2^31 - 1
ApproachTimeSpace
DFS with BoundsO(n)O(h)
In-Order TraversalO(n)O(h)
Section titled “Approach 1: DFS with Min/Max Bounds (Recommended)”
★ Recommended

Track min and max bounds as you traverse. Left child must be > min, right child must be < max.

⏱ Time O(n) 💾 Space O(h)
validate_binary_search_tree_bounds.py
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isValidBST(root: Optional[TreeNode]) -> bool:
def dfs(node: Optional[TreeNode], min_val: float, max_val: float) -> bool:
if not node: return True
if not (min_val < node.val < max_val): return False
return dfs(node.left, min_val, node.val) and dfs(node.right, node.val, max_val)
return dfs(root, float('-inf'), float('inf'))
if __name__ == "__main__":
root = TreeNode(2)
root.left, root.right = TreeNode(1), TreeNode(3)
print(isValidBST(root)) # True
🎯 Interview Favourite

In-order traversal of a valid BST yields sorted values. Track previous value and ensure it’s always increasing.

⏱ Time O(n) 💾 Space O(h)
validate_binary_search_tree_inorder.py
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isValidBST(root: Optional[TreeNode]) -> bool:
prev = [float('-inf')]
def dfs(node: Optional[TreeNode]) -> bool:
if not node: return True
if not dfs(node.left): return False
if node.val <= prev[0]: return False
prev[0] = node.val
return dfs(node.right)
return dfs(root)
if __name__ == "__main__":
root = TreeNode(2)
root.left, root.right = TreeNode(1), TreeNode(3)
print(isValidBST(root)) # True