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 descendent 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.
Distace of the closest key from H is 1 Distace of the closest key from C is 2 Distace of the closest key from E is 2 Distace of the closest key from B is 0
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 closest leaf also.
This article is contributed by Shubham. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Closest leaf to a given node in Binary Tree
- Find the closest element in Binary Search Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Find height of a special binary tree whose leaf nodes are connected
- Print the longest leaf to leaf path in a Binary tree
- Sum of all leaf nodes of binary tree
- Product of all leaf nodes of binary tree
- Count Non-Leaf nodes in a Binary Tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Print all leaf nodes of a Binary Tree from left to right
- Print all leaf nodes of a binary tree from right to left
- Print the nodes of binary tree as they become the leaf node
- Pairwise Swap leaf nodes in a binary tree
- Deepest left leaf node in a binary tree
- Given a binary tree, print all root-to-leaf paths
Improved By : shrikanth13