Print all nodes at distance K from given node: Iterative Approach
Given a binary tree, a target node and an integer K, the task is to find all the nodes that are at distance K from the given target node.
Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today!
Consider the above-given Tree, For the target node 12.
Input: K = 1
Output: 8 10 14
Input: K = 2
Output: 4 20
Input: K = 3
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 store the parent node of every node in a hash-map with the help of the Level-order traversal on the tree. Then, Simply Traverse the nodes from the Target node using Breadth-First Search on the left-child, right-child, and the parent node. At any instant when the distance of a node the from the target node is equal to K then print all the nodes of the queue.
Below is the implementation of the above approach: