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 :
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print the nodes that are just above the leaf node
- Print the nodes of binary tree as they become the leaf node
- Print all nodes at distance k from a given node
- Print all nodes at distance K from given node: Iterative Approach
- Print all leaf nodes of an n-ary tree using DFS
- Print Leaf Nodes at a given Level
- Sum of nodes on the longest path from root to leaf node
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Print all leaf nodes of a Binary Tree from left to right
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print all leaf nodes of a binary tree from right to left
- Print left and right leaf nodes separately in Binary Tree
- Print leaf nodes in binary tree from left to right using one stack
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print nodes at k distance from root
- Distance between two nodes of binary tree with node values from 1 to N
- Print nodes at k distance from root | Iterative
- Print the longest leaf to leaf path in a Binary tree
- Print all nodes except rightmost node of every level of the Binary Tree