Algo-Sim › Binary Trees & BST

All Nodes Distance K in Binary Tree

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Record each node’s parent, then BFS outward from the target through children and parents; the queue after k rounds is the answer.

Problem

Given the root of a binary tree with distinct values, a target node in it, and an integer k, return the values of every node exactly k edges away from target, in any order. Edges may be walked in either direction.

Constraints

Edge cases to test

Follow-up questions

Why record parents?
Distance k can go up through ancestors; parent links turn the tree into an undirected graph for BFS: O(n).
Can you avoid the parent map?
A DFS that returns the distance to the target lets each ancestor search its other subtree at k − d − 1.

Solution

Java

public List<Integer> distanceK(TreeNode root, TreeNode target, int k) {
    Map<TreeNode, TreeNode> parent = new HashMap<>();
    link(root, null, parent);
    Queue<TreeNode> queue = new ArrayDeque<>(List.of(target));
    Set<TreeNode> seen = new HashSet<>(List.of(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.offer(next);
            }
        }
    }
    List<Integer> result = new ArrayList<>();
    for (TreeNode node : queue) result.add(node.val);
    return result;
}

private void link(TreeNode node, TreeNode from, Map<TreeNode, TreeNode> parent) {
    if (node == null) return;
    parent.put(node, from);
    link(node.left, node, parent);
    link(node.right, node, parent);
}

Python

from collections import deque


def distance_k(root, target, k):
    parent = {}
    link(root, None, parent)
    queue, seen = deque([target]), {target}
    for _ in range(k):
        if not queue:
            break
        for _ in range(len(queue)):
            node = queue.popleft()
            for nxt in (node.left, node.right, parent[node]):
                if nxt and nxt not in seen:
                    seen.add(nxt)
                    queue.append(nxt)
    return [node.val for node in queue]


def link(node, frm, parent):
    if not node:
        return
    parent[node] = frm
    link(node.left, node, parent)
    link(node.right, node, parent)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> distanceK(TreeNode *root, TreeNode *target, int k) {
        unordered_map<TreeNode *, TreeNode *> parent;
        link(root, nullptr, parent);
        deque<TreeNode *> queue = {target};
        unordered_set<TreeNode *> seen = {target};
        for (int dist = 0; dist < k && !queue.empty(); dist++) {
            for (int size = int(queue.size()); size > 0; size--) {
                TreeNode *node = queue.front();
                queue.pop_front();
                for (TreeNode *next : {node->left, node->right, parent[node]}) {
                    if (next != nullptr && seen.insert(next).second)
                        queue.push_back(next);
                }
            }
        }
        vector<int> result;
        for (TreeNode *node : queue)
            result.push_back(node->val);
        return result;
    }

  private:
    void link(TreeNode *node, TreeNode *from, unordered_map<TreeNode *, TreeNode *> &parent) {
        if (node == nullptr)
            return;
        parent[node] = from;
        link(node->left, node, parent);
        link(node->right, node, parent);
    }
};

More Binary Trees & BST problems