AlgoInsight

DSA problem

All Nodes Distance K in Binary Tree

MediumDepth First Search (DFS)Pattern: Depth First Search (DFS)top300AmazonMicrosoftGoogleMetaApple

Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node. You can return the answer in any order. Distance is measured along tree edges and is symmetric (a parent is distance 1 from its child, just as a child is distance 1 from its parent).

The complication is that a binary tree provides downward links (left, right) but not upward links to the parent — yet a node at distance k from the target can lie above, below, or to the side of the target. We need to be able to walk upward from the target as well as downward.

The standard trick is a two-phase algorithm. Phase 1 is a DFS that builds an explicit parent map: a hashmap from each node to its parent. This converts the tree into a general (now undirected) graph in which we can navigate in any direction. Phase 2 is a BFS or DFS from target that uses three neighbors per node — left child, right child, and parent (if any) — together with a visited set so we never revisit a node. After exactly k BFS layers, every node in the current frontier is at distance k from the target.

Time and space are both O(n): each node and each edge are visited a constant number of times in both phases, and the parent map plus visited set use linear memory.

Examples

Example 1
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: Distance 2 from node 5 are nodes 7 and 4 (downward) and node 1 (via parent 3).
Example 2
Input: root = [1], target = 1, k = 3
Output: []
Explanation: A single-node tree has no other nodes, so no node is at distance 3.
Example 3
Input: root = [0,1,null,3,2], target = 2, k = 1
Output: [1]
Explanation: Node 1 is the parent of 2, so it is at distance 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dfsbfstreehash-table

Browse all DSA problems