-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindkthsmallest.cpp
More file actions
79 lines (69 loc) · 1.17 KB
/
findkthsmallest.cpp
File metadata and controls
79 lines (69 loc) · 1.17 KB
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
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node*left,*right;
Node(int x)
{
data = x;
left=right=NULL;
}
};
Node*insert(Node*root,int x)
{
if(root==NULL)
{
return new Node(x);
}
if(x<root->data)
{
root->left = insert(root->left,x);
}
else if(x>root->data)
{
root->right = insert(root->right,x);
}
return root;
}
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);
}
void printKthSmallest(Node*root,int k)
{
int count = 0;
Node*res = kthSmallest(root,k);
if(res == NULL)
{
cout<<"There are less than k nodes in the BST";
}
else
{
cout<<"K-th Smallest Element is "<<res->data;
}
}
int main()
{
Node* root = NULL;
int keys[] = { 20, 8, 22, 4, 12, 10, 14 };
for (int x : keys)
root = insert(root, x);
int k = 3;
printKthSmallest(root, k);
return 0;
}