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.
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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print nodes at k distance from root | Iterative
- Print all nodes at distance k from a given node
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Print all nodes that are at distance k from a leaf node
- Get level of a node in binary tree | iterative approach
- Deepest left leaf node in a binary tree | iterative approach
- Deepest right leaf node in a binary tree | Iterative approach
- Iterative program to find distance of a node from root
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U
- Print all neighbour nodes within distance K
- Print the last k nodes of the linked list in reverse order | Iterative Approaches
- Check for Symmetric Binary Tree (Iterative Approach)
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Iterative approach to check if a Binary Tree is Perfect
- Iterative approach to check for children sum property in a Binary Tree
- Iterative Approach to check if two Binary Trees are Isomorphic or not
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Smallest number in BST which is greater than or equal to N ( Iterative Approach)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : sanjeev2552