Print all nodes that are at distance k from a leaf node
Given a Binary Tree and a positive integer k, print all nodes that are distance k from a leaf node.
Here the meaning of distance is different from previous post. Here k distance from a leaf means k levels higher than a leaf node. For example if k is more than height of Binary Tree, then nothing should be printed. Expected time complexity is O(n) where n is the number nodes in the given Binary Tree.
The idea is to traverse the tree. Keep storing all ancestors till we hit a leaf node. When we reach a leaf node, we print the ancestor at distance k. We also need to keep track of nodes that are already printed as output. For that we use a boolean array visited.
Nodes at distance 2 are: 1 3
Time Complexity: Time Complexity of above code is O(n) as the code does a simple tree traversal.
Space Optimized Solution :
Nodes at distance 2 are : 3 1
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Another approach :
Time Complexity: O(n) as the code does a simple tree traversal.
Auxiliary Space: O(h) as the function call stack is used where h=height of the tree.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.