Problem Statement:
Given a BST and a key, find the next greater element of that key
Example:
Input:
/*
* 10
* / \
* 8 12
* / \ / \
* 2 9 11 14
*/
key = 11
Output: 12
Solution Explanation:
Add the elements into the vector and check the elements one by one to see which value is greater than the given key.
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);
for (int i = 0; i < values.size(); i++)
{
if (values[i] > target) {
return values[i];
}
}
return -1;
}
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 = 11;
cout <<solution(root, key);
return 0;
}
Output
12