Problem Description
Given the root of a binary tree, a target node (identified by its value), and an integer k, return an array of values of all nodes that have a distance k from the target node. The answer can be returned in any order.
Key Insights
- Convert the binary tree into an undirected graph so that we can easily traverse both down to the children and up to the parent.
- Use a DFS or simple recursive traversal to create an adjacency list representing the graph.
- Perform a BFS starting from the target node to explore nodes level-by-level until reaching distance k.
- Use a visited set (or equivalent) to avoid revisiting nodes and to prevent cycles.
Space and Time Complexity
Time Complexity: O(N), where N is the number of nodes in the tree. Each node is visited once when constructing the graph and once in the BFS. Space Complexity: O(N), for storing the graph and the additional data structures used in BFS and DFS.
Solution
The solution involves two main steps:
- Build an undirected graph representation of the binary tree using a DFS. For each node, add the node’s value as a key in an adjacency list and connect it with its children (if any). This creates bidirectional links between parent and child.
- Use a BFS starting from the target node and explore nodes level-by-level. Keep a counter for the current distance, and once the counter reaches k, return all node values found at that level. To avoid processing nodes more than once, maintain a set of visited nodes.