All Nodes Distance K in Binary Tree
Find every node of a binary tree that is exactly k steps away from a given node.
Given the root of a binary tree, a node of that tree called targetkktarget
Example 1
Output: [7, 4, 1]
Explanation: 7 and 4 are two steps down from 5; 1 is one step up to 3 and one step down to 1.
Example 2
Output: []
The Idea
Think of a family tree, and ask who is two steps away from you. Your grandchildren are, two steps down. So are your brothers and sisters: one step up to your parent, then one step down to another child. The problem asks the same question about a binary tree.
The input of Example 1 lists the tree row by row. The top node, the root, is 3. Its two children are 5 and 1. The next row gives the children of 5, which are 6 and 2, then those of 1, which are 0 and 8. Then come two null
Look at the picture below. The target 5 is orange. The nodes 1 step away from it are blue: its children 6 and 2, and its parent 3. The nodes 2 steps away are green: 7 and 4 below 2, and 1, which is reached by going up to 3 and down again. So the answer for k = 2 is [7, 4, 1].
Going down is easy, because each node points to its left and right child. Going up is the hard part. A tree node holds no link to its parent, yet the answer 1 is only reachable through the dashed arrow labelled "parent link". How can the search climb from 5 to 3?
Suppose every node did know its parent. Then each node would have up to three neighbours, left child, right child and parent, and up would be as easy as down. Starting at 5, we could step to all its neighbours to find the blue nodes, then step from each blue node to find the green ones. The colours spread out from the target like ripples on a pond.
Visiting nodes this way, everything 1 step away before anything 2 steps away, is called breadth-first search (BFS). On a tree it often starts at the root and moves down, as in
Solution Approach
Turning the ripples into code means settling three things: how each node finds its parent, how to spread out one step per round, and how to stop the search from walking back the way it came.
Finding each node's parent
Where does a node's parent come from, if the node does not store it? Before the search starts, one walk over the whole tree can write it down. A helper method, recordParentsHashMapparentnull
Spreading out one step per round
How does the search keep the blue nodes apart from the green ones? It keeps the nodes it has reached in a queue, a line where nodes join at the back and leave from the front. At the start of a round, the queue holds exactly the nodes of one distance. The round takes out that many nodes and puts their neighbours at the back.
In Example 1 the queue starts with only 5 in it. Round one takes 5 out and adds 6, 2 and 3. Round two takes those three out and adds 7, 4 and 1. After k rounds the queue holds the answer. If the queue runs empty first, no node is that far away, and the answer is empty.
Not walking back
Why can the search go wrong once parent links exist? From 5 the search steps up to 3, but 3 lists 5 as its left child, so the next round would step from 3 straight back to 5. A HashSetseenaddfalse
Java Solution
The method distanceK
- First, build the parent links: create the map
and callparent . It walks down the tree and stores, for every node, the node directly above it.recordParents(root, null, parent) - Create the queue, an
namedArrayDeque , and the setqueue , and putseen in both.target - Run the rounds with two loops, one inside the other. The outer loop counts the rounds in
and stops afterdist rounds or whenk is empty. The inner loop takes outqueue nodes, the number in the queue when the round starts.size - For each node taken out, look at its three neighbours:
,node.left andnode.right . A neighbour that is notparent.get(node) and thatnull accepts goes to the back ofseen.add .queue - When the rounds are over,
holds the nodesqueue steps away. Copy their values into the listk and return it.result
The mainbuildfind
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class AllNodesDistanceKInBinaryTree {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
Map<TreeNode, TreeNode> parent = new HashMap<>();
recordParents(root, null, parent);
Queue<TreeNode> queue = new ArrayDeque<>();
Set<TreeNode> seen = new HashSet<>();
queue.add(target);
seen.add(target);
for (int dist = 0; dist < k && !queue.isEmpty(); dist++) {
for (int size = queue.size(); size > 0; size--) {
TreeNode node = queue.poll();
for (TreeNode next : new TreeNode[] {node.left, node.right, parent.get(node)}) {
if (next != null && seen.add(next)) {
queue.add(next); // first visit: one edge further out
}
}
}
}
List<Integer> result = new ArrayList<>();
for (TreeNode node : queue) {
result.add(node.val);
}
return result;
}
private static void recordParents(TreeNode node, TreeNode par,
Map<TreeNode, TreeNode> parent) {
if (node == null) {
return;
}
parent.put(node, par);
recordParents(node.left, node, parent);
recordParents(node.right, node, parent);
}
// Builds a tree from the row-by-row form, where null marks a missing child.
static TreeNode build(Integer... values) {
TreeNode root = new TreeNode(values[0]);
Queue<TreeNode> waiting = new ArrayDeque<>();
waiting.add(root);
int i = 1;
while (i < values.length) {
TreeNode node = waiting.poll();
if (values[i] != null) {
node.left = new TreeNode(values[i]);
waiting.add(node.left);
}
i++;
if (i < values.length && values[i] != null) {
node.right = new TreeNode(values[i]);
waiting.add(node.right);
}
i++;
}
return root;
}
// Finds the node holding a value (values in these trees are all different).
static TreeNode find(TreeNode node, int val) {
if (node == null || node.val == val) {
return node;
}
TreeNode inLeft = find(node.left, val);
return inLeft != null ? inLeft : find(node.right, val);
}
public static void main(String[] args) {
TreeNode root = build(3, 5, 1, 6, 2, 0, 8, null, null, 7, 4);
System.out.println(distanceK(root, find(root, 5), 2));
TreeNode single = build(1);
System.out.println(distanceK(single, single, 3));
System.out.println(distanceK(root, find(root, 5), 0));
System.out.println(distanceK(root, find(root, 7), 3));
System.out.println(distanceK(root, find(root, 5), 10));
}
}
Running it prints:
[7, 4, 1]
[]
[5]
[6, 3]
[]
Look at the first line, [7, 4, 1]
The single-node tree of Example 2 prints [][5][6, 3]
The last line asks for nodes 10 steps from 5. The farthest nodes, 0 and 8, are 3 steps away, so the queue runs empty in the fourth round and the result is []
The seenseen.add(next)[5, 7, 4, 5, 5, 1]
Complexity
The work is one walk to record the parents, plus one search outward from the target.
- Time: O(n), because
visits each of the n nodes once, and the search puts each node in the queue at most once and checks only its three neighbours.recordParents - Space: O(n), because the
map holds one entry per node andparent andseen can each grow to n nodes, while the recursion ofqueue goes only as deep as the tree is tall.recordParents