> ## 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.

# Largest BST Subtree Python Solution with Tests

> Tested Python solution for LeetCode 333 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 333, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Binary Search Tree](/catalog/topics/binary-search-tree), [Dynamic Programming](/catalog/topics/dynamic-programming), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/largest-bst-subtree/description/).

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

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

## Problem

Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes.

A **Binary Search Tree (BST)** is a tree in which all the nodes follow the below-mentioned properties:

* The left subtree values are less than the value of their parent (root) node's value.
* The right subtree values are greater than the value of their parent (root) node's value.

**Note:** A subtree must include all of its descendants.

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0333.Largest%20BST%20Subtree/images/tmp.jpg)

```
Input: root = [10,5,15,1,8,null,7]
Output: 3
Explanation: The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3.
```

```
Input: root = [4,2,7,2,3,5,null,2,null,null,null,null,null,1]
Output: 2
```

### Constraints

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

**Follow up:** Can you figure out ways to solve it with `O(n)` time complexity?

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(n) — post-order pass carrying (is_bst, size, min, max)
    # Space: O(h) — recursion depth equals tree height
    def largest_bst_subtree(self, root: TreeNode[int] | None) -> int:
        def dfs(node: TreeNode[int] | None) -> tuple[bool, int, int | None, int | None]:
            if node is None:
                return True, 0, None, None
            left_bst, left_size, left_min, left_max = dfs(node.left)
            right_bst, right_size, right_min, right_max = dfs(node.right)
            if (
                left_bst
                and right_bst
                and (left_max is None or left_max < node.val)
                and (right_min is None or right_min > node.val)
            ):
                return (
                    True,
                    1 + left_size + right_size,
                    left_min if left_min is not None else node.val,
                    right_max if right_max is not None else node.val,
                )
            return False, max(left_size, right_size), None, None

        return dfs(root)[1]
```

## Complexity

| Time | Space |
| - | - |
| O(n) — post-order pass carrying (is\_bst, size, min, max) | O(h) — recursion depth equals tree height |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.