-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathkth_smallest_element.cpp
More file actions
52 lines (51 loc) · 953 Bytes
/
Copy pathkth_smallest_element.cpp
File metadata and controls
52 lines (51 loc) · 953 Bytes
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
#include<bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
node(int d)
{
data=d;
left=NULL;
right=NULL;
}
};
vector<int>v;
void inorder(node* root)
{
if(root==NULL)
return;
inorder(root->left);
v.push_back(root->data);
inorder(root->right);
}
int KthSmallestElement(node *root, int K)
{
v.clear();
inorder(root);
int ans=-1;
for(int i=0;i<v.size();i++)
{
if((i+1)==K)
{
ans=v[i];
break;
}
}
return ans;
}
int main()
{
node *root=new node(30);
root->left=new node(20);
root->right=new node(50);
root->left->left=new node(10);
root->right->left=new node(40);
root->right->right=new node(60);
root->right->right->right=new node(70);
cout<<KthSmallestElement(root,2);
return 0;
}