Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Kth largest element in BST #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions Kth largest element in BST
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

// Tree Node
struct Node {
int data;
Node *left;
Node *right;

Node(int val) {
data = val;
left = right = NULL;
}
};

// Function to Build Tree
Node* buildTree(string str)
{
// Corner Case
if(str.length() == 0 || str[0] == 'N')
return NULL;

// Creating vector of strings from input
// string after spliting by space
vector<string> ip;

istringstream iss(str);
for(string str; iss >> str; )
ip.push_back(str);

// Create the root of the tree
Node* root = new Node(stoi(ip[0]));

// Push the root to the queue
queue<Node*> queue;
queue.push(root);

// Starting from the second element
int i = 1;
while(!queue.empty() && i < ip.size()) {

// Get and remove the front of the queue
Node* currNode = queue.front();
queue.pop();

// Get the current node's value from the string
string currVal = ip[i];

// If the left child is not null
if(currVal != "N") {

// Create the left child for the current node
currNode->left = new Node(stoi(currVal));

// Push it to the queue
queue.push(currNode->left);
}

// For the right child
i++;
if(i >= ip.size())
break;
currVal = ip[i];

// If the right child is not null
if(currVal != "N") {

// Create the right child for the current node
currNode->right = new Node(stoi(currVal));

// Push it to the queue
queue.push(currNode->right);
}
i++;
}

return root;
}

int kthLargest(Node *root, int k);

int main()
{
int t;
cin>>t;
getchar();

while(t--)
{
string s;
getline(cin,s);
Node* head = buildTree(s);

int k;
cin>>k;
getchar();

cout << kthLargest( head, k ) << endl;
}
return 1;
}// } Driver Code Ends


/*The Node structure is defined as
struct Node {
int data;
Node *left;
Node *right;

Node(int val) {
data = val;
left = right = NULL;
}
};
*/

// return the Kth largest element in the given BST rooted at 'root'
vector<int> vec;
void fun(Node *root){
if(!root){return;}
fun(root->right);
vec.push_back(root->data);
fun(root->left);
}
int kthLargest(Node *root, int k)
{
//Your code here
fun(root);
sort(vec.begin(),vec.end());
int y = vec[vec.size()-k];
vec.clear();
return y;
}