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
- K'th largest element in a stream
- K'th Largest Element in BST when modification to BST is not allowed
- K'th Largest element in BST using constant extra space
- Replace every element with the least greater element on its right
- Sum of k largest elements in BST
- Largest number in BST which is less than or equal to N
- Largest BST in a Binary Tree | Set 2
- Largest number less than or equal to N in BST (Iterative Approach)
- Find the largest BST subtree in a given Binary Tree | Set 1
- Rank of an element in a stream
- Maximum element between two nodes of BST
- Find closest value for every element in array
- Ceiling in right side for every element in an array
- Smallest Greater Element on Right Side
- K'th smallest element in BST using O(1) Extra Space