Pattern visualizer
All Nodes at Distance K in Binary Tree
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. 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]..
Turn the tree into a graph with a parent map, then BFS outward in rings
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