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 target, and a whole number k, return the values of all nodes that are exactly k steps away from target. One step goes from a node to its parent or to one of its children. The values can come in any order.

Example 1
Input: root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], target = 5, k = 2
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
Input: root = [1], target = 1, k = 3
Output: []
Solution

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 entries, meaning 6 has no children, and finally 7 and 4, the children of 2.

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].

The tree of Example 1 with the target 5 in orange. 6, 2 and 3 are 1 step away, and 3 is reached by the parent link going up from 5. 7, 4 and 1 are 2 steps away, the answer for k = 2. 0 and 8 are farther.

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 Level Order Traversal. Here it starts at the target and may move in any direction. After k rounds of spreading, the nodes just reached are the answer.

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, recordParents, visits every node together with the node it came from, and stores that pair in a HashMap named parent. In Example 1 the map says that the parent of 5 is 3 and the parent of 7 is 2. The root's parent is stored as null, since nothing sits above it.

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 HashSet named seen remembers every node already reached. Its add method returns false for a node it already holds, and that node is not queued again.

Java Solution

The method distanceK works in these steps:

  1. First, build the parent links: create the map parent and call recordParents(root, null, parent). It walks down the tree and stores, for every node, the node directly above it.
  2. Create the queue, an ArrayDeque named queue, and the set seen, and put target in both.
  3. Run the rounds with two loops, one inside the other. The outer loop counts the rounds in dist and stops after k rounds or when queue is empty. The inner loop takes out size nodes, the number in the queue when the round starts.
  4. For each node taken out, look at its three neighbours: node.left, node.right and parent.get(node). A neighbour that is not null and that seen.add accepts goes to the back of queue.
  5. When the rounds are over, queue holds the nodes k steps away. Copy their values into the list result and return it.

The main method builds each tree from its row-by-row form with a helper, build, and finds the target node by its value with find. It runs both examples, then k = 0, a target at the bottom of the tree, and a k larger than the tree reaches.

Java
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:

Output
[7, 4, 1]
[]
[5]
[6, 3]
[]

Look at the first line, [7, 4, 1]. The order comes from the queue. Round one left it as 6, 2, 3, so in round two the children of 2, which are 7 and 4, join before 1, the other child of 3.

The single-node tree of Example 2 prints []: 1 has no neighbours, so the queue is empty after the first round. With k = 0 the loops never run, and [5] is the target itself. The fourth line starts at 7, at the bottom of the tree, with k = 3. Every path from 7 first climbs to 2 and 5, and the third step goes from 5 down to 6 and up to 3, giving [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 seen set matters. With the seen.add(next) test taken out, the same call on Example 1 returns [5, 7, 4, 5, 5, 1]. The target 5 comes back three times, as the parent of 6, the parent of 2 and the left child of 3.

Complexity

The work is one walk to record the parents, plus one search outward from the target.

  • Time: O(n), because recordParents 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.
  • Space: O(n), because the parent map holds one entry per node and seen and queue can each grow to n nodes, while the recursion of recordParents goes only as deep as the tree is tall.