All Nodes Distance K in Binary Tree

medium

Given the root of a binary tree, a target node value, and an integer k, return the values of all nodes that are at distance k from the target node — where distance is the number of edges on the path between two nodes. The answer may be in any order.

All node values are unique, and the target is guaranteed to exist. The tree is given in level-order (breadth-first), using null for missing children.

Hints

Distance-k nodes can be below the target or above it through ancestors.
A binary tree lacks parent links — add them, then BFS treating the tree as an undirected graph.
After k BFS levels from the target, the queue holds exactly the distance-k nodes.

Common doubts

Nodes at distance k can lie above the target — through its parent and into other subtrees — which downward-only traversal misses.
They give each node three neighbors (two children and a parent), turning the tree into an undirected graph where BFS finds all distance-k nodes.
It returns the distance from each node to the target; at an ancestor distance d away, it collects nodes k-d down the opposite subtree.

Interview follow-ups

Both root the tree as a graph and spread outward from a start node; burning tree asks for the time (max distance) to reach every node.
You'd pass the target node reference directly (the original LeetCode signature) instead of identifying it by value.

Fun facts

  • Adding parent pointers is the universal trick for turning 'distance in a rooted tree' into graph BFS.
  • The single-DFS solution is a neat example of returning information up the recursion to act at ancestors.

Asked at

AmazonFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], target = 5, k = 2
Output: [7, 4, 1]
Nodes 7 and 4 are two steps below 5; node 1 is two steps up-and-over through 3.
Example 2
Input: root = [1], target = 1, k = 0
Output: [1]
Distance 0 from the target is the target itself.
Constraints

- The number of nodes is in the range [1, 500] - 0 <= Node.val <= 500 - All Node.val are unique - 0 <= k <= 1000 - The target value exists in the tree

Solve this problem →