Print all nodes at distance k

How to solve this problem?

Hello @dsingh200021,

APPROACH:
There are two types of nodes to be considered.

  1. Nodes in the subtree rooted with the target node. For example, if the target node is 8 and k is 2, then such nodes are 10 and 14.
  2. Other nodes, maybe an ancestor of the 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 the 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 the 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 the target node, let the distance be d, now we go to another subtree (if the target was found in the 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.

image

Hope, this would help.
Give a like, if you are satisfied.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.