Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

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

Objec­tive: - Given Binary Tree, Print All The Nodes Which are X dis­tance from the Leaf Nodes

Exam­ple :

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 Prob­lem is the exten­sion of ” Print paths from root to all leaf nodes
  • Instead of print­ing all the nodes in array, print nodes which are at (pathLength-x), which will the nodes which are the x dis­tance from the leaf nodes.
  • To avoid print­ing the redun­dant val­ues, because one node can be at the x dis­tance from the mul­ti­ple leaf nodes, use boolean vis­ited[] ( sim­i­lar to path[] ) and mark it true once the node is printed.

Com­plete Code:


Out­put:

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

You may also like...