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
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 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
- Find the closest element in Binary Search Tree | Space Efficient Method
- Smallest Greater Element on Right Side
- Sum and Product of minimum and maximum element of Binary Search Tree
- Closest greater or same value on left side for every element in array
- Find closest smaller value for every element in array