Binary Search Trees: Given a BST, find median in BST

Problem Statement:

Given a BST, find the median

Example:

Input:

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

Output:

10

Solution Explanation:

We will use inorder traversal to add elements in the sorted list and then find the median

Time Complexity: O(n)
Space Complexity: O(n)

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);
}


int solution(Tree_Node* root, int target)
{

    vector<int> values;

    //add all the elements into the vector
    inorderTraversal(root, values);

	int n = values.size();
    
    // n is even
    if (n % 2 == 0)
        return values[n/2-1];
        
    // n is odd
    else
        return values[n/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);

    int key = 9;

    cout <<solution(root, key);

    return 0;
}

Output

10
Write a Comment

Leave a Comment

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