Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Second largest element in BST

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

Examples no 1 (Approach no 1)

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 ofBST

Example no 2 (Approach no 2):

Input :  The Given BST 
             
                         8
                      /    \
                     3      10
                   /  \       \
                  1    6       14      
                      /  \     /
                     4    7   13

 Find the 2nd largest number in given BST?

Program: (Implementation by using while loop)

C++




#include <iostream>
 
struct Node {
    int value;
    Node *left;
    Node *right;
};
 
int findSecondLargest(Node *root) {
    Node *current = root;
    Node *parent = nullptr;
 
    while (current->right != nullptr) {
        parent = current;
        current = current->right;
    }
 
    if (current->left != nullptr) {
        current = current->left;
        while (current->right != nullptr) {
            current = current->right;
        }
        return current->value;
    } else {
        return parent->value;
    }
}
 
int main() {
    // Example usage
    Node *root = new Node{8,
        new Node{3,
            new Node{1, nullptr, nullptr},
            new Node{6,
                new Node{4, nullptr, nullptr},
                new Node{7, nullptr, nullptr}
            }
        },
        new Node{10,
            nullptr,
            new Node{14,
                new Node{13, nullptr, nullptr},
                nullptr
            }
        }
    };
 
    int secondLargest = findSecondLargest(root);
    std::cout << "Second largest value: " << secondLargest << std::endl;
 
    return 0;
}


Python3




class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None
 
def findSecondLargest(root):
    current = root
    parent = None
 
    while current.right:
        parent = current
        current = current.right
 
    if current.left:
        current = current.left
        while current.right:
            current = current.right
        return current.value
    else:
        return parent.value
 
# Example usage
root = Node(8)
root.left = Node(3)
root.left.left = Node(1)
root.left.right = Node(6)
root.left.right.left = Node(4)
root.left.right.right = Node(7)
root.right = Node(10)
root.right.right = Node(14)
root.right.right.left = Node(13)
 
secondLargest = findSecondLargest(root)
print("Second largest value: {}".format(secondLargest))


Java




// Java code to find second largest element in BST
 
class Node {
    int value;
    Node left;
    Node right;
     
// constructor to initialize Node
    public Node(int value, Node left, Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}
 
class Main {
    public static int findSecondLargest(Node root) {
        Node current = root; // start from the root node
        Node parent = null;
 
        // Traverse down the rightmost path to find the largest element
        while (current.right != null) {
            parent = current;
            current = current.right;
        }
 
        // If the largest element has a left child, then the second largest
        // element is the rightmost element in the left subtree of the largest element
        if (current.left != null) {
            current = current.left;
             
             // traverse down the rightmost path
            while (current.right != null) {
                current = current.right;
            }
            // return the value of the second largest element
            return current.value;
        } else {
            // otherwise, return the value of the parent of the largest element
            return parent.value;
        }
    }
 
// Driver Code
    public static void main(String[] args) {
        // Example
        Node root = new Node(8,
            new Node(3,
                new Node(1, null, null),
                new Node(6,
                    new Node(4, null, null),
                    new Node(7, null, null)
                )
            ),
            new Node(10,
                null,
                new Node(14,
                    new Node(13, null, null),
                    null
                )
            )
        );
         // find the second largest element
        int secondLargest = findSecondLargest(root);
        System.out.println("Second largest value: " + secondLargest);
    }
}


Javascript




// Define a Node class to represent a node in a binary search tree
class Node {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}
 
// Define a function to find the second largest value in a binary search tree
function findSecondLargest(root) {
    let current = root;
    let parent = null;
    // Traverse to the rightmost node
    while (current.right) {
        parent = current;
        current = current.right;
    }
    // If the rightmost node has a left subtree,
    // find the rightmost node in that subtree
    if (current.left) {
        current = current.left;
        while (current.right)
            current = current.right;
        return current.value;
    } else {
        // Otherwise, return the parent of the rightmost node
        return parent.value;
    }
}
 
// Example usage
let root = new Node(8);
root.left = new Node(3);
root.left.left = new Node(1);
root.left.right = new Node(6);
root.left.right.left = new Node(4);
root.left.right.right = new Node(7);
root.right = new Node(10);
root.right.right = new Node(14);
root.right.right.left = new Node(13);
 
let secondLargest = findSecondLargest(root);
console.log(`Second largest value: ${secondLargest}`);


C#




using System;
 
public class Node {
    public int value;
    public Node left;
    public Node right;
 
    // constructor to initialize Node
    public Node(int value, Node left, Node right)
    {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}
 
public class MainClass {
    public static int FindSecondLargest(Node root)
    {
        Node current = root; // start from the root node
        Node parent = null;
 
        // Traverse down the rightmost path to find the
        // largest element
        while (current.right != null) {
            parent = current;
            current = current.right;
        }
 
        // If the largest element has a left child, then the
        // second largest element is the rightmost element
        // in the left subtree of the largest element
        if (current.left != null) {
            current = current.left;
 
            // traverse down the rightmost path
            while (current.right != null) {
                current = current.right;
            }
            // return the value of the second largest
            // element
            return current.value;
        }
        else {
            // otherwise, return the value of the parent of
            // the largest element
            return parent.value;
        }
    }
 
    // Driver Code
    public static void Main()
    {
        // Example
        Node root = new Node(
            8,
            new Node(3, new Node(1, null, null),
                     new Node(6, new Node(4, null, null),
                              new Node(7, null, null))),
            new Node(10, null,
                     new Node(14, new Node(13, null, null),
                              null)));
        // find the second largest element
        int secondLargest = FindSecondLargest(root);
        Console.WriteLine("Second largest value: "
                          + secondLargest);
    }
}


Output

Second largest value: 13

Time complexity : O(h) where h is height of BST.

Space Complexity: O(1) 

Explanation:

The code above is a C++ implementation of an algorithm to find the second largest element in a binary search tree (BST).

  • The Node struct defines the structure of a node in the binary tree, which has a value, and pointers to its left and right child nodes.
  • The findSecondLargest function takes the root node of the BST as its input and returns the second largest value stored in the tree. The function implements the algorithm described in a previous answer, which takes advantage of the property of BSTs that the largest element is stored in the rightmost node. By traversing the right subtree, we reach the largest element, and if it has a left subtree, the second largest element will be stored in the rightmost node of that subtree.
  • The function starts by initializing two pointers, current and parent, to the root node of the BST and nullptr, respectively.
  • The algorithm then enters a while loop, where current is updated to current->right and parent is updated to current until current->right is nullptr. This loop moves current to the rightmost node in the BST, which is the largest element.
  • After the loop, the code checks if current->left is nullptr or not. If current->left is not nullptr, the function enters another while loop, where current is updated to current->right until current->right is nullptr. This loop moves current to the rightmost node in the left subtree of the largest element, which is the second largest element. The value stored in this node is then returned.
  • If current->left is nullptr, the second largest element is the parent of the largest element, which is stored in parent. The value stored in parent is then returned.
  • Finally, the main function demonstrates how to use the findSecondLargest function by creating a sample BST and calling the function with its root node as input. The output of the function is then printed to the console.

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.
 


My Personal Notes arrow_drop_up
Last Updated : 13 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials