Given a binary tree, a target node in the binary tree, and an integer value k, print all the nodes that are at distance k from the given target node. No parent pointers are available.
Consider the tree shown in diagram
Input: target = pointer to node with data 8.
root = pointer to node with data 20.
k = 2.
Output : 10 14 22
If target is 14 and k is 3, then output
should be “4 20”
There are two types of nodes to be considered.
1) Nodes in the subtree rooted with target node. For example if the target node is 8 and k is 2, then such nodes are 10 and 14.
2) Other nodes, may be an ancestor of target, or a node in some other subtree. For target node 8 and k is 2, the node 22 comes in this category.
Finding the first type of nodes is easy to implement. Just traverse subtrees rooted with the target node and decrement k in recursive call. When the k becomes 0, print the node currently being traversed (See this for more details). Here we call the function as printkdistanceNodeDown().
How to find nodes of second type? For the output nodes not lying in the subtree with the target node as the root, we must go through all ancestors. For every ancestor, we find its distance from target node, let the distance be d, now we go to other subtree (if target was found in left subtree, then we go to right subtree and vice versa) of the ancestor and find all nodes at k-d distance from the ancestor.
Following is the implementation of the above approach.
Time Complexity: At first look the time complexity looks more than O(n), but if we take a closer look, we can observe that no node is traversed more than twice. Therefore the time complexity is O(n).
This article is contributed by Prasant Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Print all nodes that are at distance k from a leaf node
- Print nodes at k distance from root
- Print nodes at k distance from root | Iterative
- Count nodes within K-distance from all nodes in a set
- Find distance from root to given node in a binary tree
- Iterative program to find distance of a node from root
- Shortest distance between two nodes in BST
- Sum of cousin nodes of a given node in a BST
- Find distance between two nodes of a Binary Tree
- Sum of all the parent nodes having child node x
- Queries to find distance between two nodes of a Binary tree
- Shortest distance between two nodes in an infinite binary tree
- Identify all Grand-Parent Nodes of each Node in a Map
- Find all reachable nodes from every node present in a given set
- Sum of nodes on the longest path from root to leaf node