Problem
Given a BST (Binary search tree), find the second largest element of it.
Examples
Example 1:
|
|
|
|
Example 1:
|
|
|
|
Solution
We have seen a similar problem - Kth largest element in Binary Search Tree.
Method 1 - Find the maximum twice
If you are quite familiar with all of these, you should be able to come up with this very straightforward solution: First, find the largest element of the BST and delete it. Then, find the largest element of the current BST, which is the 2nd largest element of the original BST.
But this does modification to the tree, and also time complexity is not O(h), where h
is the height of the bst.
Method 2 - Inorder traversal and using array
Another approach can be we do the inorder traversal of the tree, and generate the array. Then, we return the second last element as the answer. But this is again bad, as time and space complexity is both O(n), where n is the number of nodes in the BST.
For eg. inorder traversal is [0, 1, 2, 3]
in example 2, and 2nd last element is 2.
Method 3 - Reverse Inorder Traversal
We need to do reverse inorder traversal, as we need second largest element, but inorder traversal goes from small to large elements. We need it in reverse order.
We can use a counter variable. Count is 1 for largest element, and we will increase it, as the element we find is less than largest element. When our count == 2, we return the answer.
Code
|
|
Complexity
- ⏰ Time complexity:
O(h)
- 🧺 Space complexity:
O(1)
Method 4 - Finding the second largest element using largest element
We can use following relation:
Traverse through the tree looking for the largest element.
- if the largest element has a left child, return the largest element of the left subtree.
- else, return the parent of the largest element.
Code
|
|