← Questions
All nodes at distance K in a binary tree
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Apple's coding round and at Meta, last asked Jun 2026. It tests trees, bfs and graphs.
Given the root of a binary tree, a target node in it and an integer k, return the values of every node exactly k edges away from the target. Edges count in both directions, so a path may go up through parents and down into other subtrees.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
distance_k(root: TreeNode, target: TreeNode, k: int) -> list[int]—targetis a node object in the tree (values may repeat, so it is not given as a value); the result is sorted ascending for a deterministic answer.
Example
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
distance_k(root, node 5, 2) -> [1, 4, 7] # 7 and 4 below, 1 through the root
distance_k(root, node 5, 0) -> [5]
distance_k(root, node 5, 10) -> []
Constraints
- Up to 500 nodes (or more if the interviewer scales it);
0 <= k <= 1000. - Node values may repeat.
Clarifying questions
- Is the target given as a node or as a value? If a value, can it repeat or be missing?
- What should
k = 0return? - Does the output order matter?
- Can I add a parent pointer, or must I leave the tree unchanged?
What a strong answer covers
- Build a parent map with one traversal (or turn the tree into an undirected adjacency list), then BFS from the target for
klevels with a visited set keyed by node identity. - O(n) time and O(n) space.
- The alternative without a parent map: a DFS that returns the distance to the target and collects nodes in the other subtree at the right depth.
- Edge cases:
k = 0,klarger than the tree's height, target is the root or a leaf, duplicate values. - Iterative traversal for deep, skewed trees.
Follow-ups
- Answer many queries
(target, k)on the same tree quickly. - Return all nodes within distance
k, not exactlyk. - Do the same on a general graph with cycles.
Where it's asked
- Apple · Coding · Last asked Jun 2026
- Meta · Technical phone screen · Last asked Jul 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding

