#98
Medium
BFS / DFS

Validate Binary Search Tree

Check whether a binary tree is a valid BST.

TreeDFS

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

1

DFS is ideal because validity depends on ancestor bounds, not just local parent-child comparisons.

2

Each subtree inherits a value range from its ancestors, and every node must stay strictly inside that range.

3

Identify the graph model and how neighbors are generated.

4

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

warning

Only comparing each node with its direct children.

warning

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.

view_weekBack to the pattern page
LeetCode 98. Validate Binary Search Tree Guide | Interview AiBox