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

# Closest Leaf in a Binary Tree Python Solution

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

LeetCode 742, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/closest-leaf-in-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 742   # by problem number
lcpy gen -s closest_leaf_in_a_binary_tree   # by problem name
```

## Problem

Given the `root` of a binary tree where every node has a **unique value** and a target integer `k`, return *the value of the nearest leaf node to the target* `k` *in the tree*.

Nearest to a leaf means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a leaf if it has no children.

In case of a tie, any leaf with the minimum distance is accepted.

### Examples

```
Input: root = [1,3,2], k = 1
Output: 2
Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.
```

```
Input: root = [1], k = 1
Output: 1
Explanation: The nearest leaf node is the root node itself.
```

```
Input: root = [1,2,3,4,null,null,null,5,null,6], k = 2
Output: 3
Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.
```

### Constraints

* The number of nodes in the tree is in the range \[1, 1000].
* 1 \<= Node.val \<= 1000
* All the values of the tree are unique.
* There exist some node in the tree where Node.val == k.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque

from leetcode_py import TreeNode


class Solution:
    # Time: O(n)
    # Space: O(n)
    def find_closest_leaf(self, root: TreeNode[int] | None, k: int) -> int:
        assert root is not None
        parent: dict[int, TreeNode[int] | None] = {id(root): None}
        q: deque[TreeNode[int]] = deque([root])
        target: TreeNode[int] | None = None
        while q:
            node = q.popleft()
            if node.val == k:
                target = node
            for child in (node.left, node.right):
                if child is not None:
                    parent[id(child)] = node
                    q.append(child)
        assert target is not None
        dist: dict[int, int] = {id(target): 0}
        q = deque([target])
        while q:
            node = q.popleft()
            if node.left is None and node.right is None:
                return node.val
            for nxt in (parent[id(node)], node.left, node.right):
                if nxt is not None and id(nxt) not in dist:
                    dist[id(nxt)] = dist[id(node)] + 1
                    q.append(nxt)
        return root.val
```

## Complexity

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

## Tags


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