Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.
You can return the answer in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2 Output: [7,4,1] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
Example 2:
Input: root = [1], target = 1, k = 3 Output: []
Constraints:
[1, 500].0 <= Node.val <= 500Node.val are unique.target is the value of one of the nodes in the tree.0 <= k <= 1000When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are standing at a specific starting node in a family tree and want to find all your relatives who are an exact number of relationship steps away. The brute force approach involves looking at every single person in the entire tree one by one and measuring the exact distance between them and your starting person.
Here's how the algorithm would work step-by-step:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, distance_k: int) -> List[int]:
all_tree_nodes = []
def collect_all_nodes(current_node):
if current_node is not None:
all_tree_nodes.append(current_node)
collect_all_nodes(current_node.left)
collect_all_nodes(current_node.right)
collect_all_nodes(root)
node_parent_map = {}
def map_parent_nodes(current_node, parent_node):
if current_node is not None:
node_parent_map[current_node] = parent_node
map_parent_nodes(current_node.left, current_node)
map_parent_nodes(current_node.right, current_node)
map_parent_nodes(root, None)
# We map paths because trees only store downward links, but distance requires bidirectional traversal
node_distances = {}
def calculate_all_distances(start_node):
visited_nodes_set = {start_node}
queue_for_bfs = [(start_node, 0)]
while queue_for_bfs:
active_node, current_distance = queue_for_bfs.pop(0)
node_distances[(start_node, active_node)] = current_distance
neighbor_nodes = [active_node.left, active_node.right, node_parent_map[active_node]]
for neighbor in neighbor_nodes:
if neighbor is not None and neighbor not in visited_nodes_set:
visited_nodes_set.add(neighbor)
queue_for_bfs.append((neighbor, current_distance + 1))
for tree_node in all_tree_nodes:
calculate_all_distances(tree_node)
final_answer_list = []
# We iterate through all nodes to check if their computed distance matches our target requirement
for tree_node in all_tree_nodes:
if node_distances.get((target, tree_node), -1) == distance_k:
final_answer_list.append(tree_node.val)
return final_answer_listBinary trees only let you move downward from parents to children, but finding nodes at a specific distance requires moving upward toward parents as well. To solve this, we can first map out the connections in both directions like a two-way street map, and then explore outward from our starting point step-by-step until we reach the target distance.
Here's how the algorithm would work step-by-step:
class Solution:
def distanceK(self, root_node, target_node, target_distance):
adjacency_map = {}
# We build a graph mapping each node to its parent and children to enable bidirectional traversal.
def build_graph(current_node, parent_node):
if current_node:
if parent_node:
adjacency_map.setdefault(current_node, []).append(parent_node)
adjacency_map.setdefault(parent_node, []).append(current_node)
build_graph(current_node.left, current_node)
build_graph(current_node.right, current_node)
build_graph(root_node, None)
queue_traversal = collections.deque([target_node])
visited_nodes = {target_node}
current_distance = 0
# We perform a breadth-first search outward layer by layer until we reach the target distance.
while queue_traversal:
if current_distance == target_distance:
return [node.val for node in queue_traversal]
for _ in range(len(queue_traversal)):
current_node = queue_traversal.popleft()
for neighbor_node in adjacency_map.get(current_node, []):
if neighbor_node not in visited_nodes:
visited_nodes.add(neighbor_node)
queue_traversal.append(neighbor_node)
current_distance += 1
# If the queue empties before reaching the target distance, no nodes exist at that depth.
return []| Case | How to Handle |
|---|---|
| Root is null or target node does not exist in the binary tree | We return an empty list immediately after verifying the target node can be found via tree traversal. |
| K is 0 | The algorithm returns a list containing only the target node value itself since the distance to itself is zero. |
| K is greater than the maximum height or depth of the tree | The traversal naturally stops when reaching null pointers and returns an empty list since no nodes are at that distance. |
| Binary tree is completely skewed forming a linked list | Converting the tree to an undirected graph via parent pointers allows us to traverse upwards and downwards without stack overflow issues. |
| Target is a leaf node | The breadth-first search will correctly only explore upwards through the parent pointer and downwards into empty child subtrees. |
| Target is the root node | The algorithm skips the parent pointer step and explores strictly downwards into both left and right subtrees up to distance k. |
| Tree contains duplicate node values | The solution must use TreeNode object references rather than primitive integer values when building the parent map and graph traversal queue. |
| Extremely large binary trees with up to 5000 nodes | Using a hash map for parent pointers and a breadth-first search queue ensures O(N) time and space complexity, scaling efficiently. |