All Nodes Distance K in Binary Tree

Pattern: Level order BFS

medium

Record each node's parent, so a node's neighbours are its left child, right child and parent. Then BFS from the target, one ring at a time, never revisiting a node. After k rings, the queue holds the answer.

The problem

Given a tree, a target node and k, return the values of all nodes exactly k edges from the target. Values are different from each other. This guide returns them in increasing order (LeetCode accepts any order). The example gives [1, 4, 7]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • Can the answer be above the target?
  • What would make this an ordinary graph search?
  • How do you avoid going back the way you came?

Hints

    Brute force, and why it fails

    For every node, compute its distance to the target through their LCA: O(n²).

    The key insight

    Parent links turn the tree into an undirected graph, where BFS finds every node at distance k in O(n).

    Dry run

    ring5

    Tree [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], target 5, k = 2. Ring 0: {5}.

    Step 1 of 4

    The plan

    record parent of every node
    ring = [target]; seen = {target}
    repeat k times: ring = unseen neighbours (left, right, parent) of nodes in ring
    return sorted values of ring
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    Linear BFS, plus sorting the answer.

    Edge cases

    • k = 0: just the target.
    • k larger than any distance: [].
    • The target is the root.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
            Map<TreeNode, TreeNode> parent = new HashMap<>();
            link(root, null, parent);               // so we can also walk upwards
            List<Integer> out = new ArrayList<>();
            Set<TreeNode> seen = new HashSet<>();
            Queue<TreeNode> q = new ArrayDeque<>();
            q.add(target);
            seen.add(target);
            for (int d = 0; d < k && !q.isEmpty(); d++) {   // BFS one ring at a time
                int size = q.size();
                for (int i = 0; i < size; i++) {
                    TreeNode node = q.poll();
                    for (TreeNode next : new TreeNode[]{node.left, node.right, parent.get(node)}) {
                        if (next != null && seen.add(next)) q.add(next);
                    }
                }
            }
            for (TreeNode node : q) out.add(node.val);
            Collections.sort(out);                  // this guide returns them in increasing order
            return out;
        }
    
        private void link(TreeNode node, TreeNode up, Map<TreeNode, TreeNode> parent) {
            if (node == null) return;
            parent.put(node, up);
            link(node.left, node, parent);
            link(node.right, node, parent);
        }
    }

    C++

    class Solution {
    public:
        vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
            unordered_map<TreeNode*, TreeNode*> parent;
            link(root, NULL, parent);               // so we can also walk upwards
            unordered_set<TreeNode*> seen;
            queue<TreeNode*> q;
            q.push(target);
            seen.insert(target);
            for (int d = 0; d < k && !q.empty(); d++) {   // BFS one ring at a time
                int size = static_cast<int>(q.size());
                for (int i = 0; i < size; i++) {
                    TreeNode* node = q.front();
                    q.pop();
                    TreeNode* nexts[3] = {node->left, node->right, parent[node]};
                    for (TreeNode* next : nexts) {
                        if (next != NULL && seen.insert(next).second) q.push(next);
                    }
                }
            }
            vector<int> out;
            while (!q.empty()) { out.push_back(q.front()->val); q.pop(); }
            sort(out.begin(), out.end());           // this guide returns them in increasing order
            return out;
        }
    
        void link(TreeNode* node, TreeNode* up, unordered_map<TreeNode*, TreeNode*>& parent) {
            if (node == NULL) return;
            parent[node] = up;
            link(node->left, node, parent);
            link(node->right, node, parent);
        }
    };

    Python

    class Solution:
        def distanceK(self, root, target, k: int) -> list[int]:
            parent = {}
    
            def link(node, up):                     # so we can also walk upwards
                if node:
                    parent[node] = up
                    link(node.left, node)
                    link(node.right, node)
    
            link(root, None)
            seen, ring = {target}, [target]
            for _ in range(k):                      # BFS one ring at a time
                nxt = []
                for node in ring:
                    for other in (node.left, node.right, parent[node]):
                        if other and other not in seen:
                            seen.add(other)
                            nxt.append(other)
                ring = nxt
            return sorted(node.val for node in ring)   # this guide returns them in increasing order

    Common mistakes

    • Walking back to a node already visited.
    • Forgetting the parent direction.

    Similar problems