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
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.
- 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
- Queries to find sum of distance of a given node to every leaf node in a Weighted Tree
- Print Leaf Nodes at a given Level
- Print all leaf nodes of an n-ary tree using DFS
- 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 all leaf nodes of a binary tree from right to left
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print left and right leaf nodes separately in Binary Tree
- Print leaf nodes in binary tree from left to right using one stack
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Print nodes at k distance from root
- Print nodes at k distance from root | Iterative
- Distance between two nodes of binary tree with node values from 1 to N
- Print the longest leaf to leaf path in a Binary tree