-
Notifications
You must be signed in to change notification settings - Fork 77
/
Find_K-th_smallest_element_in_BST.cpp
98 lines (83 loc) · 1.48 KB
/
Find_K-th_smallest_element_in_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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* Given a binary search tree find the kth largest and smallest element in Binary Search Tree.
Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.*/
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node *left,*right;
node(int val)
{
data=val;
left=NULL;
right=NULL;
}
};
node* insertBST(node *root,int val)
{
if(root==NULL)
{
return new node(val);
}
if(val<root->data)
{
root->left=insertBST(root->left,val);
}
else
{
root->right=insertBST(root->right,val);
}
return root;
}
node* kthlargest(node* root,int& k)
{
if(root==NULL)
return NULL;
node* right=kthlargest(root->right,k);
if(right!=NULL)
return right;
k--;
if(k==0)
return root;
return kthlargest(root->left,k);
}
node* kthsmallest(node* root,int &k)
{
if(root==NULL)
return NULL;
node* left=kthsmallest(root->left,k);
if(left!=NULL)
return left;
k--;
if(k==0)
return root;
return kthsmallest(root->right,k);
}
int main()
{
int arr[]={10,40,45,20,25,30,50},i;
int k=3;
node* root=NULL;
for(i=0;i<7;i++)
{
root=insertBST(root,arr[i]);
}
cout<<"\n";
int p=k;
node* large=kthlargest(root,k);
k=p;
node* small=kthsmallest(root,k);
if(large==NULL)
{
cout<<"Invalid input"<<"\n";
}
else
cout<<"kth largest element is "<<large->data<<"\n";
if(small==NULL)
{
cout<<"Invalid input"<<"\n";
}
else
{
cout<<"kth smallest element is "<<small->data<<"\n";
}
}