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:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print nodes at k distance from root | Iterative
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print all nodes at distance k from a given node
- Print all nodes that are at distance k from a leaf node
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Get level of a node in binary tree | iterative approach
- Deepest right leaf node in a binary tree | Iterative approach
- Deepest left leaf node in a binary tree | iterative approach
- Iterative program to find distance of a node from root
- Print nodes at k distance from root
- Print all neighbour nodes within distance K
- Print the last k nodes of the linked list in reverse order | Iterative Approaches
- Distance between two nodes of binary tree with node values from 1 to N
- Print the last k nodes of the linked list in reverse order | Recursive approach
- Print the nodes that are just above the leaf node
- Print the nodes of binary tree as they become the leaf node
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print all nodes except rightmost node of every level of the Binary Tree
- Iterative approach to check if a Binary Tree is Perfect
- Iterative Approach to check if two Binary Trees are Isomorphic or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.