LeetCode #98 Medium

Validate Binary Search Tree

Validate Binary Search Tree is LeetCode 98 (Medium). Given the root of a binary tree, return true if it is a valid BST:

  • every node in a node's left subtree is strictly smaller than it;
  • every node in its right subtree is strictly larger;
  • both subtrees are valid BSTs too.

Equal values are not allowed. Node values cover the whole 32-bit range, so -2³¹ and 2³¹ - 1 can appear.

Constraints
  • The number of nodes in the tree is in the range [1, 10⁴].
  • -2³¹ <= Node.val <= 2³¹ - 1
bstdfsrecursion
Open on LeetCode ↗
02

Intuition

A node must be larger than every node on its left and smaller than every node on its right, not just its two children. So a node deep in the tree is limited by all the ancestors above it.

Those limits fit in one allowed range (low, high) passed down from the parent:

  • Going left: everything there must stay below the parent, so high becomes the parent's value.
  • Going right: everything there must stay above the parent, so low becomes the parent's value.

The root may be anything, (−∞, ∞). Each node then needs a single check: is its value strictly inside its range?

How to spot this pattern

This problem is the classic case of a node whose legality depends on ancestors it never sees directly; a range passed down the recursion handles every such problem. Checking each parent against its children looks right but misses those deeper limits. The same range idea shows up in Recover BST and in building a BST from preorder.

03

Approach

Try it first

Before reading on: in [5,4,6,null,null,3,7], every parent is ordered correctly against its own children. Is it a valid BST? Which ancestor does node 3 break, and what range would have caught it?

1

Start the root with no limits

Call valid(root, -inf, inf). Nothing sits above the root, so any value is allowed there. Infinity (or a 64-bit long in C++ and Java) leaves room for node values equal to -2³¹ or 2³¹ - 1.

2

Check the node against its range

An empty subtree is valid. Otherwise, if node.val is not strictly between low and high, return false straight away. The comparison is strict on both sides because equal values make a BST invalid.

3

Narrow the range for each child

Recurse into node.left with (low, node.val) and into node.right with (node.val, high). The range keeps every limit from the ancestors, so one check per node is enough. Return true only if both subtrees are valid.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isValidBST(self, root: Optional[TreeNode]) -> bool:
▶3 def valid(node, low, high):
▶4 if not node:
▶5 return True
▶6 if not (low < node.val < high):
▶7 return False
▶8 return valid(node.left, low, node.val) and valid(
▶9 node.right, node.val, high
▶10 )
▶11 
▶12 return valid(root, float("-inf"), float("inf"))
2(−∞, ∞)13checkvalid(2, −∞, ∞)
node2the root
range(−∞, ∞)nothing above it
Each node gets an allowed range, shown in the chip beside it. The root has no ancestors, so any value is allowed. Going left will cap the range at the parent's value; going right will raise its floor.
2(−∞, ∞)13check−∞low<2node<∞high2 in (−∞, ∞) → check children
node2depth 0
range(−∞, ∞)from all ancestors
inside?yesstrictly between
2 is strictly inside (−∞, ∞), so it passes. Its children inherit a narrower range: left gets (−∞, 2), right gets (2, ∞).
2(−∞, ∞)1(−∞, 2)3check−∞low<1node<2high1 in (−∞, 2) → check children
node1depth 1
range(−∞, 2)from all ancestors
inside?yesstrictly between
1 is strictly inside (−∞, 2), so it passes. It is a leaf, so this branch is done.
2(−∞, ∞)1(−∞, 2)3(2, ∞)check2low<3node<∞high3 in (2, ∞) → check children
node3depth 1
range(2, ∞)from all ancestors
inside?yesstrictly between
3 is strictly inside (2, ∞), so it passes. It is a leaf, so this branch is done.
2(−∞, ∞)1(−∞, 2)3(2, ∞)checkevery node fits its range → return true
answertruevalid BST
Valid BST. Every node sat strictly inside the range built from all of its ancestors, and each was checked once: O(n) time.
05

Inorder traversal check

Walk the tree in inorder, which visits a BST's values in sorted order, and keep the last value seen in prev. Any value that is not larger than prev breaks the BST.

▶1class Solution:
▶2 def isValidBST(self, root: Optional[TreeNode]) -> bool:
▶3 prev = float("-inf")
▶4 
▶5 def inorder(node):
▶6 nonlocal prev
▶7 if not node:
▶8 return True
▶9 if not inorder(node.left):
▶10 return False
▶11 if node.val <= prev:
▶12 return False
▶13 prev = node.val
▶14 return inorder(node.right)
▶15 
▶16 return inorder(root)
06

Common pitfalls

Comparing each node only with its children

✗ Wrong
def valid(node):
    if not node:
        return True
    if node.left and node.left.val >= node.val:
        return False
    if node.right and node.right.val <= node.val:
        return False
    return valid(node.left) and valid(node.right)
✓ Right
def valid(node, low, high):
    if not node:
        return True
    if not (low < node.val < high):
        return False
    return valid(node.left, low, node.val) and valid(node.right, node.val, high)

In [5,4,6,null,null,3,7], node 6 has children 3 and 7, which look fine. But 3 is in the right subtree of 5 and is smaller than 5. Only a range carried down from the root catches it.

Allowing equal values

✗ Wrong
if not (low <= node.val <= high):
    return False
✓ Right
if not (low < node.val < high):
    return False

LeetCode's BST needs strictly smaller values on the left and strictly larger on the right, so [2,2,2] is not valid. With <=, it passes.

Using int limits as the starting range

✗ Wrong
return valid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);  // int low, high
✓ Right
return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);  // long low, high

A tree holding exactly 2147483647 is valid, but node.val < Integer.MAX_VALUE is false, so it gets rejected. In C++ and Java, use long limits (or null for no limit); in Python, float("inf") does the job.

07

Complexity

Time
O(n)
Space
O(h)
Each node is checked once. The recursion goes as deep as the tree's height h: about log n when the tree is balanced, up to n for a chain.
08

Validate Binary Search Tree FAQ

Is it enough to check that the inorder traversal is sorted?

Yes. A tree is a valid BST exactly when its inorder traversal is strictly increasing. You do not need to store the whole list: keep the previous value and compare as you go, as in the second method below.

Can it be done without recursion in Python?

Run an iterative inorder walk with a stack: push left children until you hit None, pop a node, check it is larger than the previous value, then move to its right child. This avoids deep recursion when the tree is a long chain.