Binary Search Trees: Given a BST, find the second largest element in the BST

Problem Statement:

Given a BST, find the second largest element in the BST

Example

Input:

    /*
     *           10
     *         /    \
     *        8      12
     *       / \    /  \
     *      2   9  11   14
     */

Output:

12

Solution Explanation:

Do an in order traversal store the elements into the array.

Return the previous to last element.

Code Solution

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;

class Tree_Node 
{
public:
	int data;
	Tree_Node* left;
	Tree_Node* right;

	Tree_Node(int x) 
	{
		data = x;
		left = nullptr;
		right = nullptr;
	}
};

void inorderTraversal(Tree_Node* root, vector<int>& values)
{
    if (!root)
        return;
    inorderTraversal(root->left, values);
    values.push_back(root->data);
    inorderTraversal(root->right, values);
}

void solution(Tree_Node* root1) 
{
    
    vector<int> arr1;
    inorderTraversal(root1, arr1);
    
	cout<<arr1[arr1.size()-2]; 

}


int main()
{

    /*
     *           10
     *         /    \
     *        8      12
     *       / \    /  \
     *      2   9  11   14
     */
    Tree_Node* root = new Tree_Node(10);
    root->left = new Tree_Node(8);
    root->right = new Tree_Node(12);
    root->left->left = new Tree_Node(2);
    root->left->right = new Tree_Node(9);
    root->right->left = new Tree_Node(11);
    root->right->right = new Tree_Node(14);
    
    solution(root);

    return 0;
}

Output

12
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *