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.

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.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single DFS pass to build graph O(n) + BFS from target O(n) in worst case

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Parent mapping O(n) + BFS queue O(w) where w is maximum width of tree

n
2n
โšก Linearithmic Space

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
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