All Nodes Distance K in Binary Tree
Difficulty: Medium · Pattern: Trees & BST · LeetCode #863
Given a binary tree, a target node in it, and an integer k, return the values of all nodes at distance exactly k from target, in any order. Distance is the number of edges on the path, and paths may go up through parents.
Examples
text
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
target = 5, k = 2 → [7, 4, 1]
target = 1, k = 3 → [6, 2] (1→3→5→6 and 1→3→5→2)Hints
- Distances can go upward, but tree nodes have no parent pointers. Add them.
- With parent links, every node has up to three neighbors (left, right, parent). Run BFS from
targetforklevels.
Approach
- DFS once to build
parent[node]. - BFS from
targetover the undirected graph{left, right, parent}with aseenset. Afterklevels, the queue holds exactly the answer.
This convert the tree to a graph trick shows up whenever a problem needs to move upward. An alternative is a single DFS that returns the distance from each node to the target and collects nodes at k - dist on the opposite side, but the BFS is easier to get right.
Complexity
Time: O(n). Space: O(n).
Python solution
from collections import deque
def distanceK(root, target, k):
parent = {}
stack = [root]
while stack:
n = stack.pop()
for c in (n.left, n.right):
if c:
parent[c] = n
stack.append(c)
q, seen = deque([target]), {target}
for _ in range(k):
for _ in range(len(q)):
n = q.popleft()
for m in (n.left, n.right, parent.get(n)):
if m and m not in seen:
seen.add(m)
q.append(m)
return [n.val for n in q]JavaScript solution
function distanceK(root, target, k) {
const parent = new Map(), stack = [root];
while (stack.length) {
const n = stack.pop();
for (const c of [n.left, n.right]) if (c) { parent.set(c, n); stack.push(c); }
}
let level = [target];
const seen = new Set([target]);
for (let d = 0; d < k; d++) {
const next = [];
for (const n of level) for (const m of [n.left, n.right, parent.get(n)]) if (m && !seen.has(m)) { seen.add(m); next.push(m); }
level = next;
}
return level.map((n) => n.val);
}