Print All The Nodes Which are X distance from the Leaf Nodes

Objective: Given Binary Tree, Print All The Nodes Which are X distance from the Leaf Nodes

Example :

Print All The Nodes Which are X distance from the Leaf Nodes

Print All The Nodes Which are X distance from the Leaf Nodes

Approach:

  • This Problem is the extension of ” Print paths from root to all leaf nodes
  • Instead of printing all the nodes in array, print nodes which are at (pathLength-x), which will the nodes which are the x distance from the leaf nodes.
  • To avoid printing the redundant values, because one node can be at the x distance from the multiple leaf nodes, use boolean visited[] ( similar to path[] ) and mark it true once the node is printed.

Complete Code:


Output:

Nodes at distance by 2 :  2  3
Nodes at distance by 1 :  4  6

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: