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

# All Nodes Distance K in Binary Tree

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

LeetCode 863, Medium. Topics: Hash Table, Tree, Depth-First Search, Breadth-First Search, Binary Tree. [View on LeetCode](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/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 863   # by problem number
lcpy gen -s all_nodes_distance_k_in_binary_tree   # by problem name
```

## Problem

Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return an array of the values of all nodes that have a distance `k` from the target node.

The value of `target` is given as an integer (all node values are unique). You can return the answer in any order.

### Examples

![Example 1](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png)

```
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
```

```
Input: root = [1], target = 1, k = 3
Output: []
```

### Constraints

* The number of nodes in the tree is in the range \[1, 500].
* 0 \<= Node.val \<= 500
* All the values `Node.val` are **unique**.
* `target` is the value of one of the nodes in the tree.
* 0 \<= k \<= 1000

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/all_nodes_distance_k_in_binary_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/all_nodes_distance_k_in_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:
    # Treat tree as undirected graph: build parent map via DFS, then BFS from
    # the target node expanding to left child, right child, and parent.
    # Time: O(n)
    # Space: O(n)
    def distance_k(self, root: TreeNode[int] | None, target: int, k: int) -> list[int]:
        parent: dict[int, TreeNode[int] | None] = {}
        target_node: TreeNode[int] | None = None

        def dfs(node: TreeNode[int] | None, par: TreeNode[int] | None) -> None:
            nonlocal target_node
            if node is None:
                return
            parent[node.val] = par
            if node.val == target:
                target_node = node
            dfs(node.left, node)
            dfs(node.right, node)

        dfs(root, None)

        if target_node is None:
            return []

        visited: set[int] = {target}
        queue: deque[tuple[TreeNode[int], int]] = deque([(target_node, 0)])
        result: list[int] = []

        while queue:
            node, dist = queue.popleft()
            if dist == k:
                result.append(node.val)
                continue
            for neighbor in (node.left, node.right, parent[node.val]):
                if neighbor is not None and neighbor.val not in visited:
                    visited.add(neighbor.val)
                    queue.append((neighbor, dist + 1))

        return result
```

## Complexity

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

## Tags

[Grind](/catalog/grind).
