Given a binary tree, a target node in the binary tree, and an integer value k, the task is to find all the nodes at a distance k from the given target node. No parent pointers are available.
Note:
- You have to return the list in sorted order.
- The tree will not contain duplicate values.
Examples:
Input: target = 2, k = 2
👁 Iterative-Postorder-Traversal
Output: 3
Explanation: Nodes at a distance 2 from the given target node 2 is 3.
Input: target = 3, k = 1
👁 Iterative-Postorder-Traversal-3
Output: 1 6 7
Explanation: Nodes at a distance 1 from the given target node 3 are 1 , 6 & 7.
Approach:
There are generally two cases for the nodes at a distance of k:
- Node at a distance k is a child node of the target node.
- Node at a distance k is the ancestor of the target node.
The idea is to first traverse the tree in level order manner and map each node to its parent node in a hashmap and find the target node. Then, starting from the target node, traverse the tree using breadth first search and print the nodes which are kth distance away from target node.
Step-by-step approach:
- Create an empty queue and push the root node into it. Create a hash map (lets say parent) which will be used to map the nodes to their parent nodes. set parent[root] = NULL.
- Traverse the tree in level order manner while queue is not empty. For each node, follow the following steps:
- If value of current node is equal to target, then set target node to current node.
- If left node exists, then map the left node to current node and push it into queue.
- Similarly, if right node exists, then map the right node to current node and push it into queue.
- Push the target node into an empty queue. Create another hash map (lets say visited) to check if a node has been visited or not. Traverse the tree using breadth first search (searching level by level). Follow the following steps:
- Find the size of the queue (lets say s). Pop 's' nodes in one iteration.
- If the value of k is greater than one. Then pop 's' nodes from queue one by one. Mark the node as visited. Check if its left node, right node and parent node has been visited or not. If not, push them to queue. After popping 's' nodes, decrement the value of k by one.
- If the value of k is equal to 0, it means all the nodes currently present in the queue are k distance away from target node. So pop each node one by one and append their values into the resultant list.
- Sort the list and return it.
Below is the implementation of the above approach:
Time Complexity: O(nlogn), for sorting the resultant array.
Auxiliary Space: O(n)
Related article: