hardTreesPure DSA~35 min
All Nodes Exactly K Edges From a Target
Given a target node in a binary tree, list every node exactly k edges away — including nodes reachable by going up through ancestors and back down other branches.
Problem
Given the root of a binary tree, a target node, and an integer k, return the values of all nodes that are at distance k from the target (distance counts edges in either direction). The order of the output does not matter.
Input
A binary tree root, a target node reference, and an integer k.
Output
A list of node values at distance exactly k.
Constraints
- 1 <= number of nodes <= 500
- 0 <= k <= 1000
- All node values are unique; target exists in the tree.
Examples
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 below 5; node 1 is two away via the root.
Example 2
Input
root = [1], target = 1, k = 3
Output
[]
No node is 3 edges from the only node.