← DSA
MEDIUM

Validate Binary Search Tree

PracticeNeetCode ↗LeetCode ↗

Given the root of a binary tree, determine whether it is a valid binary search tree: every node's value must be strictly greater than every value in its left subtree and strictly less than every value in its right subtree.

Example

Input root = [5,1,4,null,null,3,6]
Output false

Key Pointers

Step-by-Step Analysis

  1. Define a helper valid(node, low, high).
  2. Base case: if node is None, return True.
  3. If node.val doesn't satisfy low < node.val < high, return False.
  4. Recurse left with (low, node.val) and right with (node.val, high); return True only if both succeed.
  5. Call valid(root, -infinity, infinity) to start.

Complexity

Time: O(n) — Space: O(h)

Code

def isValidBST(root: TreeNode | None) -> bool:
    def valid(node: TreeNode | None, low: float, high: float) -> bool:
        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)

    return valid(root, float("-inf"), float("inf"))

Code Explanation

How the solution above works, piece by piece.

  1. valid(node, low, high): every value in this subtree must be strictly between low and high.
  2. An empty subtree is valid.
  3. If the node's value is outside its range, the tree is not a BST.
  4. Left child: same lower bound, upper bound becomes this node's value. Right child: lower bound becomes this node's value.
  5. Start with (−∞, +∞). O(n) time, O(height) stack.

Visual Walkthrough

Running it on root = [5, 1, 4, null, null, 3, 6]:

Allowed value range for each node51436(−∞, +∞)(−∞, 5)(5, +∞)each node must fit its allowed range4 is in 5's right subtree,so it must be > 5 → failsanswer: False
Going left caps the range with the parent's value; going right raises its lower bound. 4 is a child of 5 on the right, so it must be greater than 5. Checking only parent–child pairs would miss violations deeper down; carrying the range catches them.
out of range

Video Explanation

NeetCode — Depth First Search, LeetCode 98