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