Given the root of a binary tree, a target node value, and an integer k, return the values of all nodes that are at distance k from the target node — where distance is the number of edges on the path between two nodes. The answer may be in any order.
All node values are unique, and the target is guaranteed to exist. The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], target = 5, k = 2 Output: [7, 4, 1] Nodes 7 and 4 are two steps below 5; node 1 is two steps up-and-over through 3.
Input: root = [1], target = 1, k = 0 Output: [1] Distance 0 from the target is the target itself.
- The number of nodes is in the range [1, 500] - 0 <= Node.val <= 500 - All Node.val are unique - 0 <= k <= 1000 - The target value exists in the tree
Distance in a tree spreads in three directions from a node: down-left, down-right, and up toward the parent. A rooted binary tree only has downward pointers, so the fix is to also reach the parent. Two clean ways: add parent pointers and BFS outward as if the tree were an undirected graph, or a single DFS that finds the target and, on the way back up, collects nodes at the right remaining distance on the other side.
“How is distance measured?”
Number of edges on the path; the target itself is distance 0.
“Does order matter?”
No — return the values in any order.
Distance-k nodes can be below the target or up through its ancestors, so I need to move upward too.
I record parent pointers, then BFS outward from the target k levels — the nodes on the k-th level are the answer.
Worked example — tree [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], target = 5, k = 2
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
from 5, distance 2: 7 and 4 (down), 1 (up through 3)
answer: [7, 4, 1]
Ancestors and their other subtrees are reachable, so you must be able to move toward the parent.
With parent links each node has three neighbors, and plain BFS finds all nodes at distance k.
Find the target and, returning up each ancestor at distance d, collect nodes k−d down the opposite subtree.
| Parent pointers + BFS | Single DFS (find + collect) | |
|---|---|---|
| Idea | Treat the tree as undirected, BFS k levels | On the way up, collect k-d down the other side |
| Time | O(n) | O(n) |
| Space | O(n) | O(height) |
Both are O(n); the parent-BFS is the most intuitive to reason about. Full code is in the Approaches selector below.
Key takeaway
Give each node a parent pointer, then BFS from the target — the k-th level is the answer. Or, in one DFS, find the target and collect nodes k−d down the opposite subtree as you return up each ancestor. O(n).
wire parents with a DFS
BFS from target over {left, right, parent}, marking visited
after k levels, the queue holds the distance-k nodes