Be the first user to complete this post

  • 0
Add to List
Medium

81. Find Nodes X Levels Up from Leaf Nodes in a Tree

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

Example :

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

Approach:

  • This Problem is the extension of Print paths from the root to all leaf nodes
  • Instead of printing all the nodes in the array, print nodes that are at (pathLength-x), which will be the nodes that 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.
 

Output:

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