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 <= 500
Node.val
are unique.target
is the value of one of the nodes in the tree.0 <= k <= 1000
When 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:
The goal is to find all tree nodes that are a specific distance away from a target node. The brute force method explores the entire tree multiple times to achieve this. It involves figuring out the distance from every single node to both the target node and then checking if the distance matches the target distance.
Here's how the algorithm would work step-by-step:
def all_nodes_distance_k_brute_force(root, target, k_distance):
target_node = find_target_node(root, target.val)
result = []
all_nodes = get_all_nodes(root)
for node in all_nodes:
distance = distance_between_nodes(node, target_node)
# Only add to result if the distance equals to target distance
if distance == k_distance:
result.append(node)
return result
def find_target_node(root, target_value):
if not root:
return None
if root.val == target_value:
return root
left_result = find_target_node(root.left, target_value)
if left_result:
return left_result
return find_target_node(root.right, target_value)
def get_all_nodes(root):
if not root:
return []
return [root] + get_all_nodes(root.left) + get_all_nodes(root.right)
def distance_between_nodes(node1, node2):
if node1 == node2:
return 0
# Explore all possible paths to find the shortest distance
queue = [(node1, 0)]
visited = {node1}
while queue:
current_node, current_distance = queue.pop(0)
if current_node == node2:
return current_distance
neighbors = get_neighbors(current_node)
for neighbor in neighbors:
if neighbor and neighbor not in visited:
queue.append((neighbor, current_distance + 1))
visited.add(neighbor)
return float('inf')
def get_neighbors(node):
neighbors = []
if node.left:
neighbors.append(node.left)
if node.right:
neighbors.append(node.right)
# Assuming each node does not have a parent
return neighbors
The problem asks us to find all nodes at a certain distance from a given target node in a binary tree. The key insight is to treat the tree as a graph and perform a breadth-first search (BFS) starting from the target, but we need to know the parent of each node.
Here's how the algorithm would work step-by-step:
import collections
def all_nodes_distance_k(root, target, k):
parent_map = {}
def dfs(node, parent):
if node:
parent_map[node] = parent
dfs(node.left, node)
dfs(node.right, node)
dfs(root, None)
# BFS to find nodes at distance K from the target.
queue = collections.deque([(target, 0)])
seen = {target}
result = []
while queue:
node, distance = queue.popleft()
if distance == k:
result.append(node.val)
continue
# Check neighbors: left, right, and parent.
for neighbor in [node.left, node.right, parent_map[node]]:
# Only process unvisited neighbors.
if neighbor and neighbor not in seen:
seen.add(neighbor)
queue.append((neighbor, distance + 1))
return result
Case | How to Handle |
---|---|
Null root node | Return an empty list immediately as there are no nodes in the tree. |
Target node is the root node and K is 0 | Return a list containing only the root node's value. |
Target node is the root node and K is greater than 0 | Perform BFS/DFS from root to find nodes at distance K. |
K is 0 and target node is not the root | Return a list containing only the target node's value. |
K is larger than the maximum possible distance from target to any node in the tree | Return an empty list if no nodes are at distance K. |
Tree is a skewed tree (all nodes on one side) | The graph construction and BFS/DFS should handle skewed trees correctly, potentially affecting performance. |
Target node does not exist in the tree | Return an empty list if the target node is not found during the initial search. |
Tree contains duplicate values, and there are multiple nodes that equal the target value | The algorithm should be modified to handle multiple target nodes, which may require finding the distances from each occurrence and then deduplicating the result. |