Given a binary tree, a target node in the binary tree, and an integer value k, the task is to find all the nodes at a distance k from the given target node. No parent pointers are available.
[Expected Approach - 1] Using Recursion - O(nlogn) Time and O(h) Space
The idea is to traverse the binary tree using recursion and find the target node. Find all the nodes in the left and right subtree of target node that are at a distance k. Also for all the nodes in the path of target node, find all the nodes in the opposite subtree that are at the distance of (k - distance of target node).
Below is the implementation of the above approach:
Output
1 24
Time Complexity: O(nlogn), for sorting the result. Auxiliary Space: O(h), where h is the height of the tree.
[Expected Approach - 2] Using DFS with Parent Pointers - O(nlogn) Time and O(n) Space:
The idea is to recursively find the target node and map each node to its parent node. Then, starting from the target node, apply depth first search (DFS) to find all the nodes at distance k from the target node.
Below is the implementation of the above approach:
Output
1 24
Time Complexity: O(nlogn), for sorting the result. Space Complexity: O(h), where h is the height of the tree.