Skip to content

Instantly share code, notes, and snippets.

@mirsahib
Last active November 20, 2017 11:38
Show Gist options
  • Save mirsahib/09f9c70f59b10c9f12279b083dc5dadf to your computer and use it in GitHub Desktop.
Save mirsahib/09f9c70f59b10c9f12279b083dc5dadf to your computer and use it in GitHub Desktop.
display nth largest element
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
};
class Stack{
private:
Node* head;
Node* temp;
Node* curr;
public:
Stack(){
head = NULL;
temp = NULL;
curr = NULL;
}
void push(char value){
temp = new Node;
temp->data = value;
temp->next = NULL;
if(head == NULL){
head=temp;
}else{
curr = head;
while(curr->next!=NULL){
curr = curr->next;
}
curr->next = temp;
}
}
void pop(){
if(head==NULL){
cout<<"List is empty"<<endl;
}else{
curr=head;
Node* prev = NULL;
while(curr->next!=NULL){
prev = curr;
curr=curr->next;
}
prev->next = NULL;
delete curr;
}
}
//function while show only the top element of the stack
void peek(){
if(head==NULL){
cout<<"List is empty"<<endl;
}else{
curr=head;
while(curr->next!=NULL){
curr=curr->next;
}
cout<<curr->data;
}
}
void display(){
if(head==NULL){
cout<<"List is empty"<<endl;
}else{
curr = head;
while(curr!=NULL){
cout<<curr->data<<" ";
curr=curr->next;
}
}
}
};
//.........end of stack.......
class bstNode{
public:
int data;
bstNode* left;
bstNode* right;
};
class BST{
private:
bstNode* root;
Stack myStack;
bstNode* insertChild(int value,bstNode* node){
if(node==NULL){
node=new bstNode;
node->data = value;
node->left = NULL;
node->right = NULL;
}else{
if(value<node->data){
node->left = insertChild(value,node->left);
}else{
node->right = insertChild(value,node->right);
}
}
return node;
}
void inorder(bstNode* node){
if(node==NULL){
return;
}
inorder(node->left);
cout<<node->data<<" ";
inorder(node->right);
}
//populating stack with binary search tree element
//stack is populated inorder way
void insertToStack(bstNode* node){
if(node==NULL){
return;
}
insertToStack(node->left);
int x = node->data;
myStack.push(x);
insertToStack(node->right);
}
public:
BST(){
root = NULL;
}
void insertChild(int value){
root = insertChild(value,root);
}
void display(){
inorder(root);
}
void pushToStack(){
insertToStack(root);
}
void displayNthHightest(int nthValue){
for(int i=0;i<nthValue-1;i++){
myStack.pop();//discard all the element upto nthvalue-1
}
myStack.peek();//take a peek at the top element
}
void displayStack(){
myStack.display();
}
};
int main()
{
Stack myStack;
BST myTree;
myTree.insertChild(10);
myTree.insertChild(8);
myTree.insertChild(12);
myTree.insertChild(7);
myTree.insertChild(9);
myTree.insertChild(11);
myTree.insertChild(13);
myTree.pushToStack();
myTree.displayStack();
cout<<endl;
myTree.displayNthHightest(4);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment