Objective: – Given Binary Tree, Print All The Nodes Which are X distance from the Leaf Nodes
Example :
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