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

# Lowest Common Ancestor of a Binary Search Tree

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

LeetCode 235, Medium. Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree. [View on LeetCode](https://leetcode.com/problems/lowest-common-ancestor-of-a-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 235   # by problem number
lcpy gen -s lowest_common_ancestor_of_a_binary_search_tree   # by problem name
```

## Problem

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."

### Examples

![Example 1](https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png)

```
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
```

**Explanation:** The LCA of nodes 2 and 8 is 6.

![Example 2](https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png)

```
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
```

**Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

```
Input: root = [2,1], p = 2, q = 1
Output: 2
```

### Constraints

* The number of nodes in the tree is in the range `[2, 10^5]`.
* `-10^9 <= Node.val <= 10^9`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the BST.

## Solution

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

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


class Solution:
    # Time: O(log n) average, O(n) worst case
    # Space: O(1) iterative, O(log n) recursive
    def lowest_common_ancestor(
        self, root: TreeNode[int] | None, p: TreeNode[int], q: TreeNode[int]
    ) -> TreeNode[int] | None:
        while root:
            # Both nodes are in left subtree
            if p.val < root.val and q.val < root.val:
                root = root.left
            # Both nodes are in right subtree
            elif p.val > root.val and q.val > root.val:
                root = root.right
            # Split point - one node on each side or one is the root
            else:
                return root
        return None
```

## Complexity

| Time                              | Space                              |
| --------------------------------- | ---------------------------------- |
| O(log n) average, O(n) worst case | O(1) iterative, O(log n) recursive |

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