VOOZH about

URL: https://www.geeksforgeeks.org/dsa/second-largest-element-in-binary-search-tree-bst/

⇱ Second largest element in BST - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Second largest element in BST

Last Updated : 23 Jul, 2025

Given a Binary Search Tree, the task is to find the second largest element in the given BST.

Example:

Input:

πŸ‘ Second-largest-element-in-BST-1

Output:  7
Explanation: The Second Largest value in the given BST is 7.

Input:

πŸ‘ Second-largest-element-in-BST-2

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.

Comment
Article Tags: