-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathK_Largest_BST.cpp
83 lines (69 loc) · 1.5 KB
/
K_Largest_BST.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// K’th Largest Element in BST when modification to BST is not allowed
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
struct node *left;
struct node *right;
node(){
data=0;
left=right=NULL;
}
};
struct node *start=NULL;
struct node *temp;
void bst(int data){
if(start==NULL){
start = new node();
start->data = data;
}
else{
temp = start;
struct node *parent = start;
while(temp != NULL){
if(temp->data < data){
parent = temp;
temp = temp->right;
}
else if(temp->data>data){
parent = temp;
temp = temp->left;
}
}
if(parent->data < data){
parent->right = new node();
parent->right->data = data;
}
else{
parent->left = new node();
parent->left->data = data;
}
}
}
void get_element(int n){
int data=0;
for(int i=0;i<n;i++){
cin>>data;
bst(data);
}
}
void printtree(node* start,int i,int arr[]){
if(start==NULL)
return;
printtree(start->left,i,arr);
arr[i++] = start->data;
printtree(start->left,i,arr);
}
int main(){
int n=0;
cin>>n;
get_element(n);
int k=0;
cout<<"Enter the kth largest element:- ";
cin>>k;
int arr[n]={0};
printtree(start,0,arr);
for(int i=0;i<n;i++){
cout<<"i = "<<i<<" = "<<arr[i]<<endl;
}
}