All Nodes Distance K in Binary Tree
Turn the tree into a graph with a parent map, then BFS outward in rings
Distance in a tree radiates three ways from any node: into its left child, its right child, and up to its parent. Plain tree nodes have no parent pointer, so a normal downward traversal can never look back up. Fix that first with a parent map, then the problem becomes plain BFS: expand outward one ring of edges at a time until dist reaches k, and whatever is left in the queue is the answer.
Details
Animated on: root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], target = 5, k = 2 — return every node exactly k edges from target. Expected: [7, 4, 1].
Problem:All Nodes Distance K in Binary TreeMedium
Turn the tree into a graph with a parent map, then BFS outward in rings
step 1 / 12
Target is node 5. We want every node exactly k=2 edges away — up through parents as well as down through children.
1FUNCTION distanceK(root, target, k):2 parent <- MAP() built by DFS FROM root3 queue <- [target]4 visited <- {target}5 dist <- 06 WHILE queue NOT EMPTY AND dist < k:7 nextQueue <- []8 FOR EACH node IN queue:9 FOR EACH neighbor IN {node.left, node.right, parent[node]}:10 IF neighbor != null AND neighbor NOT IN visited:11 ADD neighbor TO visited AND APPEND TO nextQueue12 queue <- nextQueue13 dist <- dist + 114 RETURN values of nodes IN queue
← / → step · space play · Home restart
Every step in words
Show all 12 steps
- Target is node 5. We want every node exactly k=2 edges away — up through parents as well as down through children.
- Standard tree nodes only point downward, so first walk the whole tree from the root and record each node's parent — that turns the tree into an undirected graph we can search in any direction.
- Parent map built in O(n). Each badge is that node's parent value (the root has none).
- Start the radial search at the target itself: queue = [5], dist = 0.
- dist (0) is not yet k (2), so expand every node currently in the queue.
- dist becomes 1. Still short of k, so we expand again next round.
- dist (1) is not yet k (2), so expand every node currently in the queue.
- Node 6: look at its left child, right child and parent. nothing new, its neighbors are already visited.
- Node 2: look at its left child, right child and parent. add 7 and 4.
- Node 3: look at its left child, right child and parent. add 1.
- dist becomes 2. That equals k, so the loop stops here.
- Return the queue's values: [7, 4, 1] — every one of these is exactly k=2 edges from 5.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.