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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.