Validate Binary Search Tree
Check whether a binary tree is a valid BST.
Pattern fit
DFS is ideal because validity depends on ancestor bounds, not just local parent-child comparisons.
Key observation
Each subtree inherits a value range from its ancestors, and every node must stay strictly inside that range.
Target complexity
O(n) / O(h)
How to break down the solution cleanly
DFS is ideal because validity depends on ancestor bounds, not just local parent-child comparisons.
Each subtree inherits a value range from its ancestors, and every node must stay strictly inside that range.
Identify the graph model and how neighbors are generated.
Choose BFS for shortest unweighted distance or DFS for structure exploration.
Reference implementation
Python# Generic pattern template
from collections import deque
def bfs(start):
queue = deque([start])
visited = {start}
while queue:
node = queue.popleft()
for nxt in graph[node]:
if nxt not in visited:
visited.add(nxt)
queue.append(nxt)
def dfs(node):
visited.add(node)
for nxt in graph[node]:
if nxt not in visited:
dfs(nxt)
Common pitfalls
Only comparing each node with its direct children.
Using inclusive bounds and accidentally allowing duplicates.
Common follow-ups
How does inorder traversal provide another proof?
Why are long-range ancestor bounds necessary?
Continue with related problems
Build repeatable depth inside the BFS / DFS cluster before moving on.