From 5cc1afaa5e228ec7098f29e353859c319b97df63 Mon Sep 17 00:00:00 2001 From: Udhay <72250606+Udhay-Brahmi@users.noreply.github.com> Date: Thu, 17 Dec 2020 08:27:37 +0530 Subject: [PATCH] Create Kth largest element in BST --- Kth largest element in BST | 134 +++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 Kth largest element in BST diff --git a/Kth largest element in BST b/Kth largest element in BST new file mode 100644 index 0000000..2766bf5 --- /dev/null +++ b/Kth largest element in BST @@ -0,0 +1,134 @@ +// { Driver Code Starts +#include +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 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 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 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; +}