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
- Distance between two nodes of binary tree with node values from 1 to N
- Print nodes at k distance from root
- Print all neighbour nodes within distance K
- Print nodes at k distance from root | Iterative
- 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
- Shortest distance between two nodes in BST
- Count of nodes which are at a distance X from root and leaves
- Find distance between two nodes of a Binary Tree
- Find count of pair of nodes at even distance
- 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 an infinite binary tree
- Queries to find distance between two nodes of a Binary tree