Find the closest leaf in a Binary Tree
Given a Binary Tree and a key ‘k’, find distance of the closest leaf from ‘k’.
A / \ B C / \ E F / \ G H / \ / I J K Closest leaf to 'H' is 'K', so distance is 1 for 'H' Closest leaf to 'C' is 'B', so distance is 2 for 'C' Closest leaf to 'E' is either 'I' or 'J', so distance is 2 for 'E' Closest leaf to 'B' is 'B' itself, so distance is 0 for 'B'
The main point to note here is that a closest key can either be a descendant of given key or can be reached through one of the ancestors.
The idea is to traverse the given tree in preorder and keep track of ancestors in an array. When we reach the given key, we evaluate distance of the closest leaf in subtree rooted with given key. We also traverse all ancestors one by one and find distance of the closest leaf in the subtree rooted with ancestor. We compare all distances and return minimum.
Below is the implementation of above approach.
Distance of the closest key from H is 1 Distance of the closest key from C is 2 Distance of the closest key from E is 2 Distance of the closest key from B is 0
Time Complexity : O(N) , where N is number of nodes.
Auxiliary Space : O(N) , where N is number of nodes.
The above code can be optimized by storing the left/right information also in ancestor array. The idea is, if given key is in left subtree of an ancestors, then there is no point to call closestDown(). Also, the loop can that traverses ancestors array can be optimized to not traverse ancestors which are at more distance than current result.
Extend the above solution to print not only distance, but the key of the closest leaf also.