Second largest element in BST
Given a Binary Search Tree(BST), find the second largest element.
Input: Root of below BST 10 / 5 Output: 5 Input: Root of below BST 10 / \ 5 20 \ 30 Output: 20
Source: Microsoft Interview
The idea is similar to below post.
K’th Largest Element in BST when modification to BST is not allowed
The second largest element is second last element in inorder traversal and second element in reverse inorder traversal. We traverse given Binary Search Tree in reverse inorder and keep track of counts of nodes visited. Once the count becomes 2, we print the node.
Below is the implementation of above idea.
2nd largest element is 70
Time complexity of the above solution is O(h) where h is height of BST.
This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above