Taro Logo

All Nodes Distance K in Binary Tree

#26 Most AskedMedium
0 views
Topics:
TreesGraphsRecursionBinary Search

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:

  • The number of nodes in the tree is in the range [1, 500].
  • 0 <= Node.val <= 500
  • All the values Node.val are unique.
  • target is the value of one of the nodes in the tree.
  • 0 <= k <= 1000

Solution


Clarifying Questions

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:

  1. Are node values guaranteed to be unique throughout the binary tree, or could there be duplicate values?
  2. Is it guaranteed that the target node value actually exists within the binary tree?
  3. What should be returned if no nodes are found at distance k (e.g., should we return an empty list or null)?
  4. Are we given the target node itself as a TreeNode object, or only its integer value?
  5. Can k be 0, and if so, should the output simply be the target node's value?

Brute Force Solution

Approach

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:

  1. Begin by picking the first person in the family tree.
  2. Trace the exact path of connections from your starting person to this chosen person to count how many steps separate them.
  3. Check if that counted number of steps matches the target distance you are looking for.
  4. If the step count matches, remember this person as one of your answers.
  5. If the step count does not match, ignore them and move on.
  6. Repeat this exact counting process for every single person in the entire family tree until no one is left unchecked.
  7. Finally, gather all the people you remembered who happened to be at the exact correct distance.

Code Implementation

# 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_list

Big(O) Analysis

Time Complexity
O(n²) – For each of the n nodes in the binary tree, we must trace the exact path from the starting node to that chosen node to measure the distance. Measuring the path to a single node can take up to O(n) time in the worst-case scenario of a skewed tree. Doing this individual distance calculation for every single one of the n nodes results in approximately n * n operations. Simplifying this total yields an overall time complexity of O(n²).
Space Complexity
O(N) – To find all nodes at distance K, the brute force approach relies on several auxiliary data structures to track the family tree and remember matching relatives. Specifically, we use path-tracing variables and result lists that together store up to N nodes in the worst-case scenario. Additionally, recursive traversal or queue structures take up extra memory proportional to the tree height and total node count. As the total number of nodes N grows, these data structures scale linearly, resulting in an overall auxiliary space complexity of O(N).

Optimal Solution

Approach

Binary 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:

  1. Look at every parent-child connection in the tree and make a note of it so that you can travel both upward to the parent and downward to the children from any location.
  2. Begin your journey at the specific starting node given in the problem and keep track of where you have already visited to avoid walking in circles.
  3. Take one step outward to all directly connected neighbors, which includes children and parents, marking them as distance one away.
  4. Take another step outward from those newly reached locations to find all spots that are distance two away.
  5. Continue this outward spreading process step-by-step, treating the distance like expanding ripples in a pond, until you reach the exact target distance.
  6. Gather all the final locations you landed on once you finish the exact number of steps required, and report them as your answer.

Code Implementation

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 []

Big(O) Analysis

Time Complexity
O(n) – First, we traverse all n nodes in the binary tree to build the undirected graph mapping using a breadth-first or depth-first search, which takes O(n) time. Next, we perform a breadth-first search starting from the target node, visiting each of the n nodes and their edges at most once. Summing these two linear passes together yields approximately 2n total operations, which simplifies to O(n).
Space Complexity
O(n) – To enable upward movement, we use a hash map to store parent pointers for all N nodes in the tree. We also use a visited set and a queue for breadth-first search, both of which store at most N nodes at any given time. Finally, the recursion stack used during the tree traversal to build the parent map can reach a maximum depth of N in the worst-case skewed tree scenario. Summing these data structures up, the total auxiliary space complexity scales linearly with the number of nodes N.

Edge Cases

Root is null or target node does not exist in the binary tree
How to Handle:
We return an empty list immediately after verifying the target node can be found via tree traversal.
K is 0
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The breadth-first search will correctly only explore upwards through the parent pointer and downwards into empty child subtrees.
Target is the root node
How to Handle:
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
How to Handle:
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
How to Handle:
Using a hash map for parent pointers and a breadth-first search queue ensures O(N) time and space complexity, scaling efficiently.
0/45 completed