> For the complete documentation index, see [llms.txt](https://joshualbarb.gitbook.io/leetcode-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://joshualbarb.gitbook.io/leetcode-problems/binary-search-trees/untitled.md).

# Validate Binary Search Trees

## Problem

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

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

{% hint style="info" %}
For example:

```
    5
   / \
  1   4
     / \
    3   6

Input: [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.
```

{% endhint %}

## Solution

```
class Solution:
    def isValidBST(self, root: TreeNode) -> bool:
        self.prev = None
        self.val = True
        self.helper(root, self.val)
        return self.val
    def helper(self, root, val):
        if root is None:
            return 
        self.helper(root.left, val)
        if self.prev != None:
            if self.prev.val >= root.val:
                self.val = False
                return
        self.prev = root
        self.helper(root.right, val)
            
#Time: O(log n) which is the height
#Space: O(log n) as well
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/binary-search-trees/untitled.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
