All Nodes Distance K in Binary Tree - Problem

Imagine you're standing at a specific node in a binary tree and need to find all nodes that are exactly k steps away from your current position. You can move to parent nodes, left children, or right children - each move counts as one step.

Given the root of a binary tree, a target node value, and an integer k, return an array containing the values of all nodes that are exactly distance k from the target node.

The beauty of this problem is that distance can be measured in any direction - up to parents or down to children!

Example: If target node has value 5 and k=2, you need to find all nodes that require exactly 2 steps to reach from node 5, whether going through parents, children, or a combination of both.

Input & Output

example_1.py — Basic Tree
$ Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
💡 Note: Nodes at distance 2 from target node 5 are: 7 (5→6→7), 4 (5→2→4), and 1 (5→3→1). The path can go through parents or children.
example_2.py — Single Node
$ Input: root = [1], target = 1, k = 3
Output: []
💡 Note: There are no nodes at distance 3 from the target node 1, since the tree only has one node.
example_3.py — Distance 0
$ Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 0
Output: [5]
💡 Note: At distance 0 from target node 5, only the target node itself qualifies.

Constraints

  • The number of nodes in the tree is in the range [1, 500]
  • 0 ≤ Node.val ≤ 500
  • All values Node.val are unique
  • target is the value of one of the nodes in the tree
  • 0 ≤ k ≤ 1000

Visualization

Tap to expand
TARGETABCXYBFS Ripple Effect● Level 0 (k=0): Target● Level 1 (k=1): A, B, C● Level 2 (k=2): X, YEach ripple represents one more step of distance from target
Understanding the Visualization
1
Build the Network
Create parent-child connections so every node knows its neighbors
2
Start Spreading
Begin BFS from target node, like ripples in a pond
3
Level-by-Level
Each BFS level represents one more step of distance
4
Collect Results
After k levels, collect all nodes in the current BFS queue
Key Takeaway
🎯 Key Insight: Trees are just restricted graphs. Add parent pointers to enable bidirectional BFS, then distance k becomes k levels of BFS expansion.
Asked in
Facebook 85 Amazon 72 Google 68 Microsoft 45 Apple 32
425.6K Views
High Frequency
~18 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen