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

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

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

## Problem

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

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

\<img alt="" src="[https://assets.leetcode.com/uploads/2018/12/14/binarytree.png](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)" style="width: 200px; height: 190px;" />

```
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
```

\<img alt="" src="[https://assets.leetcode.com/uploads/2018/12/14/binarytree.png](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)" style="width: 200px; height: 190px;" />

```
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
```

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

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

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/lowest_common_ancestor_of_a_binary_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/lowest_common_ancestor_of_a_binary_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)
    def lowest_common_ancestor(
        self, root: TreeNode[int], p: TreeNode[int], q: TreeNode[int]
    ) -> TreeNode[int]:
        result = self._lca(root, p, q)
        assert result is not None
        return result

    def _lca(
        self, root: TreeNode[int] | None, p: TreeNode[int], q: TreeNode[int]
    ) -> TreeNode[int] | None:
        if root in (p, q) or not root:
            return root

        left = self._lca(root.left, p, q)
        right = self._lca(root.right, p, q)

        if left and right:
            return root
        return left or right
```

## Complexity

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

## Tags

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