Scrivio Interview library
TreesTrees and binary search treesReported 22 times · 16 min read · updated 14 November 2026

Print every node at distance K from a given node in a binary tree.

1What distance means in a tree, seen as a family

Think of a family tree drawn on a wall. Who is two steps away from you? Your grandparents, two steps up. Your grandchildren, two steps down. And your brothers and sisters, one step up to your parent and one step down again. Notice that a step can go either way, up to a parent or down to a child. That is all this problem asks, and we will come back to this family more than once.

Let us fix the words. A binary tree is a set of nodes, each holding a value and pointing to at most two nodes below it, its left child and its right child. The node at the top is the root. The distance between two nodes is the number of edges, the lines between a parent and a child, on the path from one to the other.

Our example has root 3 with children 5 and 1. Node 5 has children 6 and 2, node 2 has children 7 and 4, and node 1 has children 0 and 8. The given node, called the target, is 5, and K is 2. Let us find the answer by hand. Going down two steps from 5 we pass 2 and reach 7 and 4. Going down via 6 we stop after one step, because 6 has no children. Going up one step we reach 3, and from 3 one step down the other side reaches 1. So the answer is 7, 4 and 1.

Notice which nodes are not in it. 6, 2 and 3 are only one step from 5. 0 and 8 are three steps away, up to 3, down to 1, down again. And 5 itself is zero steps away.

PictureThe example tree, the target and the answer

The target 5 is marked as looked at; the three nodes two steps from it are the answer.

  1. 351620874
    target
    5
    k
    2
    answer
    [7, 4, 1]

    1From 5, two steps down reach 7 and 4, and one step up to 3 then one step down reach 1. The answer is [7, 4, 1].

What to assume

Is the target given as a node or as a value?
We assume a node reference.
Do nodes have parent pointers?
We assume not, which is the usual case.
What if K is 0?
Then the answer is the target alone.
What if no node is that far away?
We return an empty list.
Does the order matter?
We assume not.

The problem is smaller than it looks. Downward steps are easy, because every node already points to its children. The only real difficulty is the upward step, because a node in Java has no idea who its parent is. Once we solve that, the rest is spreading out step by step, as we just did by hand.

A careful candidate asks a few questions first. Is the target given as a node or as a value? We assume a node reference. Do nodes have parent pointers? We assume not, which is the usual case. What if K is 0? Then the answer is the target alone. What if no node is that far away? We return an empty list. Does the order matter? We assume not.

2How to recognise the pattern behind this tree question

A beginner who sees the word tree usually writes a recursive function that starts at the root and goes down. Here that habit gets stuck. Start at 5 and go down, and you find 7 and 4, but you can never find 1, because the way to 1 goes up through 3, and a downward walk never goes up. So the first clue is that our usual tree tools only go one way, and this question needs both ways.

The second clue is the phrase distance K from a given node. The question does not care about left or right, parent or child; it only cares how many steps away a node is. When direction stops mattering, a tree is really just a set of points joined by lines, which is called a graph. Each node simply has up to three neighbours: its left child, its right child and its parent.

The third clue is the word every, with an exact distance. We want all the nodes at one exact number of steps. Think of news passing through the family by telephone. You call everyone one step away. Each of them calls everyone one step away from them who has not heard yet. After two rounds of calls, the people who heard in the second round are exactly the ones two steps from you. A search that spreads out in rounds like this is called breadth-first search, or BFS.

So the clues point to the trees family, and to the pattern of turning a tree into a graph and searching it breadth-first. The general rule to carry away is this: when a tree problem needs to move upward and nodes have no parent pointers, first build a map from each node to its parent, and when it asks for nodes at an exact distance or the fewest steps, spread out in rings with a queue.

Some methods look similar but fit less well. A depth-first walk can also work on the graph, but it wanders far before coming back and must filter by depth, while BFS stops cleanly at ring K. There is also a clever recursion without a parent map, described at the end, but it juggles distances returned from each side and is hard to get right under pressure.

3The brute force, measuring every node one at a time

The honest first attempt, the brute force, asks the question directly for every node: how far is it from the target? To answer that without parent pointers we use paths from the root. The path from 3 to the target 5 is [3, 5]. The path from 3 to node 1 is [3, 1]. The two paths agree on their first node, 3, and then part. The distance is the number of steps each path takes after they part, added together: one step from 3 to 5 and one from 3 to 1, so 2.

Let us check it on node 7. Its path is [3, 5, 2, 7], and the target's path is [3, 5]. They agree on 3 and 5, two nodes. The path to 7 has two more steps and the path to 5 has none, so the distance is 2. The rule works for nodes below the target and for nodes across the tree alike.

Java
static List<Integer> distanceKBrute(Node root, Node target, int k) {
List<Node> toTarget = new ArrayList<>();
pathTo(root, target, toTarget); // root ... target
List<Integer> out = new ArrayList<>();
for (Node u : allNodes(root)) {
List<Node> toU = new ArrayList<>();
pathTo(root, u, toU); // a fresh search for every node
int common = 0; // how long the two paths agree
while (common < toU.size() && common < toTarget.size()
&& toU.get(common) == toTarget.get(common)) common++;
int dist = (toU.size() - common) + (toTarget.size() - common);
if (dist == k) out.add(u.val);
}
return out;
}
// Fills path with the nodes from n down to goal; returns false if goal is not below n.
static boolean pathTo(Node n, Node goal, List<Node> path) {
if (n == null) return false;
path.add(n);
if (n == goal || pathTo(n.left, goal, path) || pathTo(n.right, goal, path)) return true;
path.remove(path.size() - 1); // not down this way: step back
return false;
}

Here allNodes is a small helper that lists every node of the tree. Now let us count. Each path is found by a search from the root that tries left and then right, stepping back when it misses. We ran this version with a counter: one search for the target and one for each of the 9 nodes, 47 node visits in all, to report 3 nodes.

In general, each of the n searches can visit up to n nodes, so the time is O(n squared), read as order n squared. The space is O(h) for the path and the recursion, where h is the height of the tree.

So where is the waste? We measure every node in full, even 0 and 8, which are further than K and could never be in the answer. And every search starts again from the root. What we really want is to start at the target and spread outward only K steps, never touching anything further. For that we need the one thing the node class does not give us: a way to step up.

4Getting to the parent map and the spreading search

Let us give the tree its upward steps first. One walk from the root visits every node, and as it goes down from a node to a child, it knows the node it came from. So it writes down, in a HashMap, the parent of each node: 5 and 1 have parent 3, 6 and 2 have parent 5, and so on, with null for the root. A HashMap works like the index at the back of a book: give it a node and it answers with the parent at once.

Now the spreading. We put the target in a queue, a line where nodes join at the back and are served from the front, and we read the length of the line at the start of each round, so we know exactly which nodes belong to this ring. For each of them we look at its three neighbours and send the new ones to the back of the line. After one round the line holds the nodes at distance 1, after two rounds those at distance 2. After K rounds, the line is the answer.

A beginner might ask why we need a visited set at all. Let us try without it and see what we lose. In round 1, node 5 sends 6, 2 and 3. In round 2, node 6 sends its parent, 5, straight back into the line, and so do 2 and 3. We ran this version, and it answered [5, 7, 4, 5, 5, 1]: the target itself, three times over. In the family, it is like your brother calling you back with your own news.

So we keep a visited set, the list of people who have already heard. A node joins the line only if it is not yet in the set, and we add it to the set at the moment it joins. Marking at the moment of joining, rather than of serving, is a good habit. In a tree either works, but in a graph with loops two nodes of the same ring can share a neighbour, and marking late would let it join the line twice.

Why is the answer right? In a tree there is exactly one path between any two nodes, so a node's distance from the target is fixed. The search reaches every node first along that path, one ring per step, and the visited set stops it from ever being added again later. So after K rounds the line holds every node at distance K and nothing else. If the line empties early, there is nobody that far away, and we return an empty list.

5Watching the news spread from node 5

The picture plays the method on our tree with target 5 and K = 2. The first frame shows the parent map being written. After that, the node being served is marked as looked at, the nodes waiting in the line as compared, and nodes already served as finished. The panel shows the line, the round and the visited set.

Watch the third frame closely. Node 5 sends three nodes into the line, and one of them, 3, is above it. That upward step is what the parent map buys us.

Step throughSpreading out from node 5, one ring at a time

The node being served is marked as looked at, nodes waiting in the line as compared, and served nodes as finished.

  1. 351620874
    parent map
    5->3, 1->3, 6->5, 2->5
    more
    0->1, 8->1, 7->2, 4->2
    root 3
    no parent

    1First one walk from the root writes down every node's parent. Now each node can step up as well as down.

  2. 351620874
    dist
    0
    line
    [5]
    visited
    5

    2The search starts at the target, node 5. It is the only node at distance 0, so the line holds just 5, and 5 is marked as visited.

  3. 351620874
    dist
    1
    line
    [6, 2, 3]
    visited
    5, 6, 2, 3

    3Round 1, size 1. We serve 5 and look at its three neighbours: left 6, right 2 and parent 3. None is visited, so all three join the line.

  4. 351620874
    dist
    2
    line
    [2, 3]
    skipped
    5, visited

    4Round 2, size 3. We serve 6. It has no children, and its parent 5 is already visited, so nothing joins the line.

  5. 351620874
    dist
    2
    line
    [3, 7, 4]
    visited
    5, 6, 2, 3, 7, 4

    5We serve 2. Its children 7 and 4 are new, so they join the line. Its parent 5 is visited, so the search does not walk back.

  6. 351620874
    dist
    2
    line
    [7, 4, 1]
    visited
    5, 6, 2, 3, 7, 4, 1

    6We serve 3, reached by going up. Its left child is 5, already visited; its right child 1 is new and joins. 3 is the root, so it has no parent.

  7. 351620874
    k
    2
    answer
    [7, 4, 1]

    7Two rounds are done and dist equals k, so the loop stops. The line holds exactly the nodes two steps from 5: [7, 4, 1]. Nodes 0 and 8 were never touched.

In round 2, every served node tries to send 5 back: 6 and 2 through their parent link, and 3 through its left child. Each time the visited set refuses it. Only 7, 4 and 1 are new, and they make the line [7, 4, 1].

Notice the last frame too. Nodes 0 and 8 were never served and never measured. The search stopped at ring 2, which is exactly the waste of the brute force removed.

6The complete Java program

Here is the whole program, with a small Node class, the distanceK method, the helper that records parents, and a main that asks for distances 2, 3, 0 and 9 from node 5. Each comment shows what that line prints.

Java
import java.util.*;
public class DistanceK {
static class Node {
int val;
Node left, right;
Node(int val, Node left, Node right) { this.val = val; this.left = left; this.right = right; }
Node(int val) { this(val, null, null); }
}
static List<Integer> distanceK(Node root, Node target, int k) {
Map<Node, Node> parent = new HashMap<>();
recordParents(root, null, parent); // lets us walk upward
Deque<Node> queue = new ArrayDeque<>(List.of(target));
Set<Node> visited = new HashSet<>(List.of(target));
for (int dist = 0; dist < k && !queue.isEmpty(); dist++) {
int size = queue.size(); // one ring at a time
for (int i = 0; i < size; i++) {
Node n = queue.poll();
for (Node next : new Node[] {n.left, n.right, parent.get(n)}) {
if (next != null && visited.add(next)) queue.add(next);
}
}
}
List<Integer> out = new ArrayList<>();
for (Node n : queue) out.add(n.val); // the ring at distance k
return out;
}
private static void recordParents(Node node, Node par, Map<Node, Node> parent) {
if (node == null) return;
parent.put(node, par);
recordParents(node.left, node, parent);
recordParents(node.right, node, parent);
}
public static void main(String[] args) {
// 3
// / \
// 5 1
// / \ / \
// 6 2 0 8
// / \
// 7 4
Node five = new Node(5, new Node(6), new Node(2, new Node(7), new Node(4)));
Node root = new Node(3, five, new Node(1, new Node(0), new Node(8)));
System.out.println(distanceK(root, five, 2)); // [7, 4, 1]
System.out.println(distanceK(root, five, 3)); // [0, 8]
System.out.println(distanceK(root, five, 0)); // [5]
System.out.println(distanceK(root, five, 9)); // []
}
}

Let us read distanceK in the order it runs. It first makes the parent map and fills it with recordParents, which visits a node, writes down its parent, and calls itself on both children, passing the node itself as their parent. The root is given null as its parent.

Next, the queue starts holding the target, and the visited set starts holding the target, so it can never be added again. The for loop counts rounds with dist, and it stops either after k rounds or when the line runs empty.

Inside, size freezes the length of this ring. For each node we serve, we try its three neighbours: n.left, n.right and parent.get(n). The test next != null skips missing children and the root's missing parent. visited.add(next) does two jobs in one call: it returns true and marks the node only if it was not there before, so a node joins the line exactly once.

When the loop ends, the line holds the ring at distance k, and we copy their values into a list. So main prints [7, 4, 1], then [0, 8] for three steps, then [5] for zero steps, and [] for nine steps, where the line runs empty before nine rounds.

7How much it costs, and the cases at the edges

Let us count on the example first. Recording parents visits all 9 nodes once. The search then served only 4 nodes, 5, 6, 2 and 3, and looked at three neighbours for each. Against 47 visits for the brute force, that is far less. For n nodes, the parent walk is O(n) and the search serves each node at most once, so the time is O(n).

The parent map holds n entries, and the visited set and the line together hold at most n nodes, so the extra space is O(n). The recursion that records parents goes as deep as the tree, O(h); for a very deep tree we would record parents with a loop and our own stack instead.

Comparing the ways to find nodes at distance K
ApproachTimeExtra space
Brute force: measure every node by pathsO(n^2)O(h)
Parent map, then BFS for K ringsO(n)O(n)
Recursion returning distances (FAQ)O(n)O(h)

When K is 0, the loop never runs and the line still holds the target, so we return [5]. When K is larger than any distance, the line runs empty and we return [], as the fourth line of main shows. When the target is the root, parent.get returns null, and the null check simply skips it. A target that is a leaf has no children, so it can only spread upward, which the map allows.

8Follow-up questions

Can it be done without a parent map?

Yes, with one recursion that returns how far the target is below each node, or -1 if it is not below it. At the target we collect nodes K steps down and return 1 to the parent. When a node hears that the target is d steps down its left side, it adds itself if d equals K, and otherwise collects nodes K - d - 1 steps down its right side, then returns d + 1 upward. The same holds for the right side. It is O(n) time and O(h) space, but easy to get wrong.

What if the target is given as a value rather than a node?

We find the node first. While recordParents walks the tree, it can also check each value and remember the node that matches. Then the search runs as before. If values can repeat, we must ask which node is meant, since each could give a different answer.

What is the most common mistake?

Forgetting the visited set. Then a node and its parent keep adding each other, and nodes closer than K appear in the answer, as the [5, 7, 4, 5, 5, 1] result showed. A second slip is to forget to put the target itself in the set at the start, which lets its children and parent send it back in round 2.

9Conclusion

We found every node at distance K by giving the tree upward steps with a parent map, and then spreading out from the target in rounds with a queue and a visited set, so that after K rounds the queue held exactly the answer. It takes O(n) time and O(n) space. The clue to remember is a distance from a given node rather than from the root: treat the tree as a graph with parent, left and right as neighbours, and search breadth-first.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the setup: the target is a node reference, nodes have no parent pointers, K of 0 returns the target, and order does not matter. A first approach measures each node's distance by comparing its path from the root with the target's path, but that is a fresh search per node, O(n squared).

Then, if they want more

Because the answer can lie above the target, I treat the tree as an undirected graph. First I walk the tree once and store each node's parent in a HashMap. Then I run a breadth-first search from the target. Each node's neighbours are its left child, its right child and its parent.

I process the queue one round at a time by reading its size, and I only add a neighbour if it is not in the visited set, marking it when it joins. Without that set, a node and its parent would keep adding each other.

After K rounds the queue holds exactly the nodes at distance K, which I return; if it empties early, I return an empty list. That is O(n) time and O(n) space for the map, the set and the queue.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 22 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Print every node at distance K from a given node in a binary tree.": https://scrivio-interview-library.netlify.app/data-structures/solutions/print-every-node-at-distance-k-from-a-given-node-in-a-binary-tre-45f83a/