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
Visualization
Time & Space Complexity
Single DFS pass to build graph O(n) + BFS from target O(n) in worst case
Parent mapping O(n) + BFS queue O(w) where w is maximum width of tree
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