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
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.
- K'th Largest Element in BST when modification to BST is not allowed
- Find k-th smallest element in BST (Order Statistics in BST)
- Two nodes of a BST are swapped, correct the BST | Set-2
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST
- K'th Largest element in BST using constant extra space
- Largest element smaller than current element on left for every element in Array
- Find the largest BST subtree in a given Binary Tree | Set 1
- Largest BST in a Binary Tree | Set 2
- Sum of k largest elements in BST
- Largest number in BST which is less than or equal to N
- Largest number less than or equal to N in BST (Iterative Approach)
- K'th smallest element in BST using O(1) Extra Space
- Maximum element between two nodes of BST
- A program to check if a binary tree is BST or not
- Sorted order printing of a given array that represents a BST
- Print BST keys in the given range
- Sorted Linked List to Balanced BST
- Sorted Array to Balanced BST
- Check if each internal node of a BST has exactly one child