Leetcode 863: All Nodes Distance K in Binary Tree

grid47
grid47
Exploring patterns and algorithms
Aug 12, 2024 7 min read

Given a binary tree, a target node within the tree, and a non-negative integer k, determine all the nodes that are exactly k edges away from the target node. Return these node values as a list in any order.
Problem
Approach
Steps
Complexity
Input: The input includes the root of a binary tree, a target node within the tree, and an integer k.
Example: root = [1,2,3,4,5,null,6], target = 2, k = 1
Constraints:
• The binary tree has between 1 and 500 nodes.
• All node values are unique and in the range [0, 500].
• The target node is guaranteed to exist in the tree.
• 0 <= k <= 1000.
Output: Return a list of all node values that are k edges away from the target node.
Example: Output: [4, 5, 1]
Constraints:
• Output can be in any order.
• If no nodes are at distance k, return an empty list.
Goal: Identify all nodes exactly k edges away from the given target node in the binary tree.
Steps:
• Store parent-child relationships of all nodes using a map.
• Perform a breadth-first search (BFS) or depth-first search (DFS) starting from the target node.
• Track visited nodes to avoid revisiting and looping.
• Stop the search when the depth equals k and collect the values of nodes at this depth.
Goal: Ensure all constraints of the input and expected output are satisfied.
Steps:
• The tree must be well-formed with no duplicate node values.
• The target node must exist within the tree.
• The value of k must be within the specified range.
Assumptions:
• The binary tree is finite with no cyclic references.
• Node values are distinct.
• The tree includes the specified target node.
Input: Input: root = [1,2,3,4,5,null,6], target = 2, k = 1
Explanation: Nodes at distance 1 from target node 2 are nodes 4, 5, and 1. Output: [4, 5, 1].

Input: Input: root = [7], target = 7, k = 3
Explanation: The tree contains only one node, so no nodes are at distance 3. Output: [].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus