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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find the largest BST subtree in a given Binary Tree | Set 1
- Find k-th smallest element in BST (Order Statistics in BST)
- K'th smallest element in BST using O(1) Extra Space
- K'th Largest Element in BST when modification to BST is not allowed
- K'th largest element in a stream
- Replace every element with the least greater element on its right
- Maximum element between two nodes of BST
- Find the closest element in Binary Search Tree
- Largest BST in a Binary Tree | Set 2
- Largest number in BST which is less than or equal to N
- Maximum Unique Element in every subarray of size K
- Largest number less than or equal to N in BST (Iterative Approach)
- Rank of an element in a stream
- K'th Largest element in BST using constant extra space
- Sum of k largest elements in BST