All Nodes Distance K in a Binary Tree solution explained
To find all nodes at distance K from a target in a binary tree, first record each node's parent so the tree can be walked in every direction, then run a breadth-first search from the target that steps to the left child, the right child and the parent, skipping nodes already visited. The nodes in the queue after exactly K rounds are the answer. It runs in O(n) time and O(n) space.
By Evin JohnPublished 8 min read
The problem, restated
You receive the root of a binary tree, a reference to one node in it called the target, and a non-negative integer k. Return the values of all nodes whose distance from the target is exactly k, where distance is the number of edges on the path between them. The path may go up through parents and back down another branch. The order of the returned values does not matter. We assume node values are unique, which is the usual statement and makes the output unambiguous.
7
/ \
2 9
/ \ \
4 1 3
/ \
6 8
k = 0 -> [2]
k = 1 -> [4, 1, 7]
k = 2 -> [6, 8, 9]
k = 3 -> [3]
k = 5 -> []At k = 2 two of the answers are below the target (6 and 8, through node 1) and one is reached by going up to 7 and down the other side to 9. That upward move is what a plain recursive descent from the target cannot do.
Why it shows up in interviews
Most tree problems only travel down. This one checks whether you notice that a tree is just a graph with directed links, and whether you can fix that by adding the missing direction. Interviewers also want to hear the visited set, because once parents are linked a BFS can bounce between a node and its parent forever. Related prompts that use the same idea:
- Time to burn a tree. Fire starts at one node and spreads one edge per minute; the answer is the farthest distance from that node, found with the same parent-linked BFS.
- Nearest leaf to a node. BFS from the node in all directions and stop at the first leaf.
- Distance between two nodes. Find their lowest common ancestor and add the two depths below it, or BFS from one to the other.
- Only the target's value is given. Find the node first with a search, which is one more O(n) pass.
A slower first idea
For every node, compute its distance to the target and keep it if the distance is k. One way to get a distance is to record the path from the root to each node, strip the shared prefix of the two paths, and add up what remains. Building one root path costs O(h), so checking all n nodes costs O(n·h), which becomes O(n²) on a skewed tree. It is correct and easy to verify, which makes it useful as a mental check, but it does far more work than needed.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def distance_k_by_paths(root, target, k):
paths = {}
def record(node, path):
if node is None:
return
path = path + [node]
paths[node] = path
record(node.left, path)
record(node.right, path)
record(root, [])
to_target = paths[target]
result = []
for node, path in paths.items():
shared = 0
while (shared < len(path) and shared < len(to_target)
and path[shared] is to_target[shared]):
shared += 1
if (len(path) - shared) + (len(to_target) - shared) == k:
result.append(node.val)
return resultThe efficient approach: parent links, then BFS
Walk the tree once and store each node's parent in a dictionary keyed by the node object. Now every node has up to three neighbours: left, right and parent. Start a breadth-first search at the target with a visited set containing it. Expand the queue one full level per round, adding unvisited neighbours. After k rounds the queue holds exactly the nodes at distance k, because BFS reaches each node first along its shortest path, and in a tree there is only one path anyway. If the queue runs empty before k rounds, the answer is an empty list.
from collections import deque
def distance_k(root, target, k):
parent = {root: None}
stack = [root]
while stack:
node = stack.pop()
for child in (node.left, node.right):
if child:
parent[child] = node
stack.append(child)
queue = deque([target])
seen = {target}
for _ in range(k):
for _ in range(len(queue)):
node = queue.popleft()
for nxt in (node.left, node.right, parent[node]):
if nxt and nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return [node.val for node in queue]function distanceK(root, target, k) {
const parent = new Map([[root, null]]);
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
for (const child of [node.left, node.right]) {
if (child) {
parent.set(child, node);
stack.push(child);
}
}
}
let level = [target];
const seen = new Set([target]);
for (let step = 0; step < k && level.length > 0; step++) {
const next = [];
for (const node of level) {
for (const nb of [node.left, node.right, parent.get(node)]) {
if (nb && !seen.has(nb)) {
seen.add(nb);
next.push(nb);
}
}
}
level = next;
}
return level.map((node) => node.val);
}Keying the maps by node objects rather than values keeps the code correct even if values repeat. There is also a one-pass recursive answer that avoids the parent map: a function returns the distance from each subtree's root to the target (or -1 if the target is not inside), and when an ancestor learns it is d steps away, it collects nodes at depth k minus d minus 1 in its other subtree. It uses O(h) space beyond the output but is much harder to get right under pressure.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Root-path comparison for every node | O(n·h) | O(n·h) for stored paths |
| Parent map plus BFS | O(n) | O(n) |
| Build an adjacency list, then BFS | O(n) | O(n) |
| Recursive distance-returning DFS | O(n) | O(h) recursion plus output |
Edge cases
- k = 0: the answer is the target alone.
- The target is the root: no upward moves exist, and the answer is the depth-k level under it.
- The target is a leaf: almost everything is reached by going up first.
- k larger than any distance in the tree: return an empty list, and stop early once the queue empties.
- A single-node tree: [target] for k = 0, empty otherwise.
- A deep skewed tree: the iterative parent walk avoids the recursion limit that a recursive version could hit in Python.
Mistakes to avoid
- Searching only below the target, which misses everything reached through a parent.
- Forgetting the visited set, so the BFS walks from child to parent and back again.
- Counting the distance in nodes instead of edges, which is off by one.
- Treating the BFS as finished when the queue is empty without checking whether k rounds have run.
- Mapping parents by value when values may repeat, which mixes up different nodes.
How to explain it out loud
Fictional example
- Candidate
- Distance can go up through the parent, but my nodes only point down. I will do one pass to store each node's parent in a hash map.
- Candidate
- Now each node has three neighbours, so this is BFS on an undirected graph. I expand one level per step, with a visited set so I never step back to where I came from.
- Candidate
- After k levels the queue is the answer. Each node is visited at most once, so O(n) time and space.
- Interviewer
- Could you do it without the hash map?
- Candidate
- Yes, with a recursion that returns how far each subtree's root is from the target and then searches the other side at the remaining depth, but I would start with the clearer version.
Related walkthroughs
Is Graph Bipartite runs the same kind of BFS on an explicit graph. Binary Tree Level Order Traversal is the level-by-level loop used here, restricted to downward edges. Delete Node in a BST also leans on knowing a node's parent, and Sum Root to Leaf Numbers passes information in only one direction, which is the limitation this problem works around. Alien Dictionary goes one step further: there the graph has to be built from scratch before any search can start.
Where Natively fits
For practice on Mac or Windows, Natively can read a tree problem like this one from a screenshot and, when you ask, point you toward the missing parent direction without handing over the code. Because it transcribes your mock session, you can review whether you explained the visited set before the interviewer had to ask about it. See the AI interview assistant for the full picture.
Questions people ask
How do you find all nodes at distance K in a binary tree?
Record each node's parent in a hash map, then run a breadth-first search from the target that moves to the left child, right child and parent, skipping visited nodes. The queue after k rounds is the answer.
Why are parent pointers needed?
Tree links only point down, but nodes at distance k can be above the target or in a sibling subtree. The parent map lets the search move upward.
What is the time complexity of All Nodes Distance K?
O(n) time and O(n) space: one pass to record parents and one BFS that visits each node at most once.
Can it be solved without a parent map?
Yes, with a recursive search that returns each subtree's distance to the target and then collects nodes at the remaining depth on the other side. It is harder to write correctly.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
