All Nodes Distance K in Binary Tree
Problem
You are given the root of a binary tree, a reference to one of its nodes called target, and a non-negative integer k. Return the values of every node whose distance from target is exactly k, where distance is the number of edges on the path between the two nodes. Nodes above target count just as much as nodes below it. Any order is acceptable.
- The tree has at most 800 nodes, and all node values are distinct.
targetis always a node that appears somewhere in the tree.kis a non-negative integer and may exceed the tree's diameter.
Examples
root = [8, 4, 2, 9, 6, 1, 5, None, None, 3, 7],target = 4,k = 2→[2, 3, 7]. Two edges up-and-over (4 → 8 → 2) reach 2; two edges down through 6 reach 3 and 7.- Same tree,
target = 4,k = 0→[4]. Distance zero is the target itself. root = [9],target = 9,k = 3→[]. Nothing is that far away.
Hints
- Going down from
targetis a normal traversal. What stops you from going up the same way? - If every node knew its parent, the tree would be an undirected graph with at most three neighbours per node. What algorithm finds everything at exactly distance
kin such a graph? - One DFS to record parent pointers in a map, then BFS from
targetwith a visited set, stopping afterklevels.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Sign in with your email — no purchase — and this question opens in full, along with 12 others.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395