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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Print the nodes of binary tree as they become the leaf node
- Print all nodes at distance k from a given node
- 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
- Distance between two nodes of binary tree with node values from 1 to N
- Print Leaf Nodes at a given Level
- 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 all leaf nodes of a Binary Tree from left to right
- 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 )
- Print nodes at k distance from root
- Print nodes at k distance from root | Iterative
- Print the longest leaf to leaf path in a Binary tree
- Closest leaf to a given node in Binary Tree