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
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Closest leaf to a given node in Binary Tree
- Print the longest leaf to leaf path in a Binary tree
- Construct XOR tree by Given leaf nodes of Perfect 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
- Find maximum GCD value from root to leaf in a Binary tree
- Find all root to leaf path sum of a Binary Tree
- Find K smallest leaf nodes from a given Binary Tree
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Program to count leaf nodes in a binary tree
- Given a binary tree, print all root-to-leaf paths
- Deepest left leaf node in a binary tree
- Root to leaf paths having equal lengths in a Binary Tree
- Iterative program to count leaf nodes in a Binary Tree
- Sum of all leaf nodes of binary tree
- Pairwise Swap leaf nodes in a binary tree
- Deepest left leaf node in a binary tree | iterative approach