Given a Binary Tree and a node x in it, find distance of the closest leaf to x in Binary Tree. If given node itself is a leaf, then distance is 0.
Input: Root of below tree And x = pointer to node 13 10 / \ 12 13 / 14 Output 1 Distance 1. Closest leaf is 14. Input: Root of below tree And x = pointer to node 13 10 / \ 12 13 / \ 14 15 / \ / \ 21 22 23 24 /\ /\ /\ /\ 1 2 3 4 5 6 7 8 Output 2 Closest leaf is 12 through 10.
We strongly recommend you to minimize your browser and try this yourself first.
The idea is to first traverse the subtree rooted with give node and find the closest leaf in this subtree. Store this distance. Now traverse tree starting from root. If given node x is in left subtree of root, then find the closest leaf in right subtree, else find the closest left in left subtree. Below is the implementation of this idea.
The closest leaf to the node with value 13 is at a distance of 2
Time Complexity of this above solution is O(n) as it does at most two traversals of given Binary Tree.
This article is contributed by Ekta Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Find the closest leaf in a Binary Tree
- Delete the last leaf node in a Binary Tree
- Deepest left leaf node in a binary tree
- Print the nodes of binary tree as they become the leaf node
- Deepest right leaf node in a binary tree | Iterative approach
- Deepest left leaf node in a binary tree | iterative approach
- Create a binary tree from post order traversal and leaf node array
- Print the longest leaf to leaf path in a Binary tree
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Find the closest element in Binary Search Tree
- Minimum time to burn a Tree starting from a Leaf node
- Sum of all leaf nodes of binary tree
- Count Non-Leaf nodes in a Binary Tree
- Product of all leaf nodes of binary tree
- Print all leaf nodes of a Binary Tree from left to right
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Pairwise Swap leaf nodes in a binary tree
- Print all leaf nodes of a binary tree from right to left
- Program to count leaf nodes in a binary tree