Skip to problem
←

All Nodes Distance K in Binary Tree

Medium 0 attempts

You're given the root of a binary tree, a target node within that tree, and an integer k. Treating the tree as an undirected graph (so you can move toward parents as well as children), return the values of every node that is exactly k edges away from target.

Function contract

Implement distanceK(root, target, k). The runner converts the level-order root array into nodes with val, left, and right fields. The target value selects the corresponding node object in that tree.

Output: An array of values of all nodes exactly k edges from target, in any order. Return [] if none exist.

Example 1

Input
root = [3,5,1,6,2,0,8,null,null,7,4]
target = 5
k = 2
Output
[7,4,1]

Example 2

Input
root = [1]
target = 1
k = 0
Output
[1]
Visual Aid
Two edges from node 5
351620874Target: 5 · k = 2 · Result: 7, 4, 1

Paths 5 → 2 → 7, 5 → 2 → 4, and 5 → 3 → 1 each contain two edges.

Constraints
  • 1 <= number of nodes <= 500
  • 0 <= Node.val <= 500
  • All values are unique
  • 0 <= k <= 1000
  • target is a node in the given tree

BFS from Target with Parent Pointers

Build a parent map, then BFS from the target node K levels.

javascript
function distanceK(root, target, k) {
  const parents = new Map();
  function dfs(node, parent) {
    if (!node) return;
    parents.set(node, parent);
    dfs(node.left, node); dfs(node.right, node);
  }
  dfs(root, null);
  const visited = new Set(), q = [target];
  visited.add(target);
  let dist = 0;
  let head = 0;
  while (head < q.length && dist < k) {
    const size = q.length - head; dist++;
    for (let i = 0; i < size; i++) {
      const n = q[head++];
      for (const next of [n.left, n.right, parents.get(n)]) {
        if (next && !visited.has(next)) { visited.add(next); q.push(next); }
      }
    }
  }
  return q.slice(head).map(n => n.val);
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript