> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Validate Binary Search Tree Python Solution

> Tested Python solution for LeetCode 98 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 98, Medium. Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree. [View on LeetCode](https://leetcode.com/problems/validate-binary-search-tree/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 98   # by problem number
lcpy gen -s validate_binary_search_tree   # by problem name
```

## Problem

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

A **valid BST** is defined as follows:

* The left subtree of a node contains only nodes with keys **strictly less than** the node's key.
* The right subtree of a node contains only nodes with keys **strictly greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg)

```
Input: root = [2,1,3]
Output: true
```

![Example 2](https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg)

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

**Explanation:** The root node's value is 5 but its right child's value is 4.

### Constraints

* The number of nodes in the tree is in the range `[1, 10^4]`.
* `-2^31 <= Node.val <= 2^31 - 1`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/validate_binary_search_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/validate_binary_search_tree/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque

from leetcode_py import TreeNode


class Solution:
    @classmethod
    def validate(cls, node: TreeNode[int] | None, min_val: float, max_val: float) -> bool:
        if not node:
            return True
        if node.val <= min_val or node.val >= max_val:
            return False
        return cls.validate(node.left, min_val, node.val) and cls.validate(
            node.right, node.val, max_val
        )

    # Time: O(n)
    # Space: O(h)
    def is_valid_bst(self, root: TreeNode[int] | None) -> bool:
        return self.validate(root, float("-inf"), float("inf"))


class SolutionDFS:
    # Time: O(n)
    # Space: O(h)
    def is_valid_bst(self, root: TreeNode[int] | None) -> bool:
        if not root:
            return True

        stack = [(root, float("-inf"), float("inf"))]

        while stack:
            node, min_val, max_val = stack.pop()
            if node.val <= min_val or node.val >= max_val:
                return False
            if node.right:
                stack.append((node.right, node.val, max_val))
            if node.left:
                stack.append((node.left, min_val, node.val))

        return True


class SolutionBFS:
    # Time: O(n)
    # Space: O(w) where w is max width
    def is_valid_bst(self, root: TreeNode[int] | None) -> bool:
        if not root:
            return True

        queue = deque([(root, float("-inf"), float("inf"))])

        while queue:
            node, min_val, max_val = queue.popleft()
            if node.val <= min_val or node.val >= max_val:
                return False
            if node.right:
                queue.append((node.right, node.val, max_val))
            if node.left:
                queue.append((node.left, min_val, node.val))

        return True
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(h)  |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
