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

# Find Mode in Binary Search Tree

> Tested Python solution for LeetCode 501 with 19 pytest cases. Generate a practice environment with lcpy.

LeetCode 501, [Easy](/catalog/easy). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Binary Search Tree](/catalog/topics/binary-search-tree), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/find-mode-in-binary-search-tree/description/).

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

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

## Problem

Given the `root` of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

If the tree has more than one mode, return them in **any order**.

Assume a BST is defined as follows:

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

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg)

```
Input: root = [1,null,2,2]
Output: [2]
```

```
Input: root = [0]
Output: [0]
```

### Constraints

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

**Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count.)

## Solution

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

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


class Solution:
    # Time: O(n)
    # Space: O(h) recursion stack; no counter map, only the output list
    def find_mode(self, root: TreeNode[int] | None) -> list[int]:
        modes: list[int] = []
        max_count = 0
        count = 0
        prev: TreeNode[int] | None = None

        def inorder(node: TreeNode[int] | None) -> None:
            nonlocal max_count, count, prev
            if node is None:
                return
            inorder(node.left)
            if prev is not None and prev.val == node.val:
                count += 1
            else:
                count = 1
            if count > max_count:
                max_count = count
                modes.clear()
                modes.append(node.val)
            elif count == max_count:
                modes.append(node.val)
            prev = node
            inorder(node.right)

        inorder(root)
        return modes
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(h) recursion stack; no counter map, only the output list |

## Tags


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