Open In App
Related Articles

Second largest element in BST

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given a Binary Search Tree (BST), find the second largest element. 

Example:

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. 

C++

// C++ program to find 2nd largest element in BST
#include<bits/stdc++.h>
using namespace std;
 
struct Node
{
    int key;
    Node *left, *right;
};
 
// A utility function to create a new BST node
Node *newNode(int item)
{
    Node *temp = new Node;
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// A function to find 2nd largest element in a given tree.
void secondLargestUtil(Node *root, int &c)
{
    // Base cases, the second condition is important to
    // avoid unnecessary recursive calls
    if (root == NULL || c >= 2)
        return;
 
    // Follow reverse inorder traversal so that the
    // largest element is visited first
    secondLargestUtil(root->right, c);
 
    // Increment count of visited nodes
    c++;
 
    // If c becomes k now, then this is the 2nd largest
    if (c == 2)
    {
        cout << "2nd largest element is "
             << root->key << endl;
        return;
    }
 
    // Recur for left subtree
    secondLargestUtil(root->left, c);
}
 
// Function to find 2nd largest element
void secondLargest(Node *root)
{
    // Initialize count of nodes visited as 0
    int c = 0;
 
    // Note that c is passed by reference
    secondLargestUtil(root, c);
}
 
/* A utility function to insert a new node with given key in BST */
Node* insert(Node* node, int key)
{
    /* If the tree is empty, return a new node */
    if (node == NULL) return newNode(key);
 
    /* Otherwise, recur down the tree */
    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);
 
    /* return the (unchanged) node pointer */
    return node;
}
 
// Driver Program to test above functions
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
    Node *root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    secondLargest(root);
 
    return 0;
}

                    

Java

class Node {
    int key;
    Node left, right;
 
    Node(int item) {
        key = item;
        left = right = null;
    }
}
 
public class Main {
    // A function to find 2nd largest element in a given tree.
    static void secondLargestUtil(Node root, int c) {
        // Base cases, the second condition is important to
        // avoid unnecessary recursive calls
        if (root == null || c >= 2)
            return;
 
        // Follow reverse inorder traversal so that the
        // largest element is visited first
        secondLargestUtil(root.right, c);
 
        // Increment count of visited nodes
        c++;
 
        // If c becomes k now, then this is the 2nd largest
        if (c == 2) {
            System.out.println("2nd largest element is " + root.key);
            return;
        }
 
        // Recur for left subtree
        secondLargestUtil(root.left, c);
    }
 
    // Function to find 2nd largest element
    static void secondLargest(Node root) {
        // Initialize count of nodes visited as 0
        int c = 0;
 
        // Note that c is passed by reference
        secondLargestUtil(root, c);
    }
 
    // A utility function to insert a new node with given key in BST
    static Node insert(Node node, int key) {
        /* If the tree is empty, return a new node */
        if (node == null)
            return new Node(key);
 
        /* Otherwise, recur down the tree */
        if (key < node.key)
            node.left = insert(node.left, key);
        else if (key > node.key)
            node.right = insert(node.right, key);
 
        /* return the (unchanged) node pointer */
        return node;
    }
 
    // Driver Program to test above functions
    public static void main(String[] args) {
        /* Let us create following BST
            50
           /  \
          30   70
         / \  / \
        20 40 60 80 */
        Node root = null;
        root = insert(root, 50);
        insert(root, 30);
        insert(root, 20);
        insert(root, 40);
        insert(root, 70);
        insert(root, 60);
        insert(root, 80);
 
        secondLargest(root);
    }
}

                    

Python3

# Python3 code to find second largest
# element in BST
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.key = data
        self.left = None
        self.right = None
         
# A function to find 2nd largest
# element in a given tree.
def secondLargestUtil(root, c):
     
    # Base cases, the second condition
    # is important to avoid unnecessary
    # recursive calls
    if root == None or c[0] >= 2:
        return
 
    # Follow reverse inorder traversal so that
    # the largest element is visited first
    secondLargestUtil(root.right, c)
 
    # Increment count of visited nodes
    c[0] += 1
 
    # If c becomes k now, then this is
    # the 2nd largest
    if c[0] == 2:
        print("2nd largest element is",
                              root.key)
        return
 
    # Recur for left subtree
    secondLargestUtil(root.left, c)
 
# Function to find 2nd largest element
def secondLargest(root):
     
    # Initialize count of nodes
    # visited as 0
    c = [0]
 
    # Note that c is passed by reference
    secondLargestUtil(root, c)
 
# A utility function to insert a new
# node with given key in BST
def insert(node, key):
     
    # If the tree is empty, return a new node
    if node == None:
        return Node(key)
 
    # Otherwise, recur down the tree
    if key < node.key:
        node.left = insert(node.left, key)
    elif key > node.key:
        node.right = insert(node.right, key)
 
    # return the (unchanged) node pointer
    return node
 
# Driver Code
if __name__ == '__main__':
     
    # Let us create following BST
    #         50
    #     /     \
    #     30     70
    #     / \ / \
    # 20 40 60 80
    root = None
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    secondLargest(root)
 
# This code is contributed by PranchalK

                    

C#

using System;
 
// C# code to find the second largest element in a BST
 
// A binary tree node
public class Node
{
    public int Data { get; set; }
    public Node Left { get; set; }
    public Node Right { get; set; }
 
    public Node(int data)
    {
        Data = data;
        Left = Right = null;
    }
}
 
public class BinarySearchTree
{
    // Root of the BST
    public Node Root { get; set; }
 
    // Constructor
    public BinarySearchTree()
    {
        Root = null;
    }
 
    // Function to insert new nodes
    public void Insert(int data)
    {
        Root = InsertNode(Root, data);
    }
 
    /* A utility function to insert a new node with a given 
    key in BST */
    private Node InsertNode(Node node, int data)
    {
        /* If the tree is empty, return a new node */
        if (node == null)
        {
            Root = new Node(data);
            return Root;
        }
 
        /* Otherwise, recur down the tree */
        if (data < node.Data)
            node.Left = InsertNode(node.Left, data);
        else
            node.Right = InsertNode(node.Right, data);
 
        return node;
    }
 
    // class that stores the value of count
    private class Counter
    {
        private readonly BinarySearchTree outerInstance;
 
        public Counter(BinarySearchTree outerInstance)
        {
            this.outerInstance = outerInstance;
        }
 
        public int Count { get; set; }
    }
 
    // Function to find the 2nd largest element
    private void FindSecondLargestElement(Node node, Counter counter)
    {
        // Base cases, the second condition is important to
        // avoid unnecessary recursive calls
        if (node == null || counter.Count >= 2)
            return;
 
        // Follow reverse inorder traversal so that the
        // The largest element is visited first
        FindSecondLargestElement(node.Right, counter);
 
        // Increment count of visited nodes
        counter.Count++;
 
        // If counter becomes k now, then this is the 2nd largest
        if (counter.Count == 2)
        {
            Console.Write("The 2nd largest element is " + node.Data);
            return;
        }
 
        // Recur for Left subtree
        FindSecondLargestElement(node.Left, counter);
    }
 
    // Function to find 2nd largest element
    public void GetSecondLargestNode(Node node)
    {
        // object of counter class
        Counter counter = new Counter(this);
        FindSecondLargestElement(Root, counter);
    }
 
    // Driver function
    public static void Main(string[] args)
    {
        BinarySearchTree bst = new BinarySearchTree();
 
        /* Let us create the following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
 
        bst.Insert(50);
        bst.Insert(30);
        bst.Insert(20);
        bst.Insert(40);
        bst.Insert(70);
        bst.Insert(60);
        bst.Insert(80);
 
        bst.GetSecondLargestNode(bst.Root);
    }
}
 
// This code is contributed by Shrikant13
// This class is edited by Alireza Maleki

                    

Javascript

<script>
 
// JavaScript code to find second largest
// element in BST
 
// A binary tree node
class Node {
    constructor(d)
    {
        this.data = d;
        this.left = this.right = null;
    }
}
 
 
 
    // Root of BST
    var root = null;
 
  
 
    // function to insert new nodes
     function insert(data)
    {
        this.root = this.insertRec(this.root, data);
    }
     
    /* A utility function to insert a
    new node with given key in BST */
    function insertRec(node , data)
    {
        /* If the tree is empty, return a new node */
        if (node == null) {
            this.root = new Node(data);
            return this.root;
        }
 
        /* Otherwise, recur down the tree */
        if (data < node.data) {
            node.left = this.insertRec(node.left, data);
        } else {
            node.right = this.insertRec(node.right, data);
        }
        return node;
    }
 
    // class that stores the value of count
     class count {
     constructor(){
        this.c = 0;
        }
    }
 
    // Function to find 2nd largest element
    function secondLargestUtil(node,  C)
    {  
        // Base cases, the second condition is important to
        // avoid unnecessary recursive calls
        if (node == null || C.c >= 2)
            return;
             
        // Follow reverse inorder traversal so that the
        // largest element is visited first
        this.secondLargestUtil(node.right, C);
         
         // Increment count of visited nodes
        C.c++;
         
        // If c becomes k now, then this is the 2nd largest
        if (C.c == 2) {
            document.write("2nd largest element is "+
                                              node.data);
            return;
        }
         
         // Recur for left subtree
        this.secondLargestUtil(node.left, C);
    }
 
    // Function to find 2nd largest element
    function secondLargest(node)
    {  
        // object of class count
        var C = new count();
        this.secondLargestUtil(this.root, C);
    }
 
    // Driver function
     
         
        /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
        
        insert(50);
        insert(30);
        insert(20);
        insert(40);
        insert(70);
        insert(60);
        insert(80);
 
        secondLargest(root);
 
// This code contributed by aashish1995
 
</script>

                    

Output
2nd largest element is 70

Time complexity : O(h) where h is height of BST. 
Space Complexity: O(h) for call stack where h is height of BST



Last Updated : 27 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads