![]() |
VOOZH | about |
Given a Binary Tree and a positive integer K, print all nodes that are distance K from a leaf node. Here K distance from a leaf means K levels higher than a leaf node. For example, if K is more than the height of the Binary Tree, then nothing should be printed.
Examples:
To solve the problem follow the below idea:
We can store the nodes in the path of our recursion and whenever we reach a leaf node, then print the Kth node in the saved path
Follow the below steps to solve the problem:
Below is the implementation of the above approach:
Nodes at distance 2 are: 1 3
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach 2: Iterative Solution
In this approach, we use an iterative method to traverse the binary tree using a stack. We maintain a stack of pairs, where each pair consists of a node and its depth. We start by pushing the root node and its depth onto the stack. Then, we repeatedly pop a node from the stack and push its left and right children, along with their depths, onto the stack. When we encounter a leaf node, we check its depth and see if it is at a distance k from the current node. If it is, we print the current node.
Here's the codes for this approach:
1 3
Time Complexity:
In the worst case, we visit every node in the binary tree once. For each node, we append its value to path and false to visited, which takes O(1) time. If the node is a leaf node, we check its depth and mark the corresponding node in visited if necessary, which also takes O(1) time. Finally, we push its left and right children onto st, which takes O(1) time each. Thus, the time complexity of the algorithm is O(n), where n is the number of nodes in the binary tree.
Space Complexity:
The space used by the algorithm is proportional to the maximum depth of the binary tree. In the worst case, the binary tree is a skewed tree, in which case the maximum depth is n. In this case, the size of path and visited is O(n), and the size of the stack st is also O(n). Thus, the space complexity of the algorithm is O(n). However, in the best case, the binary tree is a balanced tree, in which case the maximum depth is log(n). In this case, the space complexity is O(log(n)).