Output: 20 Explanation: The Second Largest value in the given BST is 20
Approach:
The idea is similar to 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 approach:
Output
7
Time complexity: O(h),where h is the height of the tree. In the worst case (for a skewed tree), this can become O(n), where n is the number of nodes. Auxiliary Space: O(h), for recursion call stack where h is the height of the tree. In the worst case (for a skewed tree), this can become O(n), where n is the number of nodes.