-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathkth_smallest.cpp
More file actions
67 lines (53 loc) · 1.16 KB
/
kth_smallest.cpp
File metadata and controls
67 lines (53 loc) · 1.16 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
//Find k-th smallest element in BST
#include <iostream>
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* small(Node* root, int& k)
{
if (root == NULL)
return NULL;
Node* left = small(root->left, k);
if (left != NULL)
return left;
k--;
if (k == 0)
return root;
return small(root->right, k);
}
void ShowSmall(Node* root, int k)
{
int count = 0;
Node* res = small(root, k);
if (res == NULL)
cout << "There are less than k nodes in the BST";
else
cout << "K-th Smallest Element is " << res->data; // 2nd smallest number in BST is 21
}
int main()
{
Node* root = NULL;
int keys[] = { 88,21,15,32,72,50 }; //Inorder or Ascending Order : 15,21,32,50,72,80
for (int x : keys)
root = insert(root, x);
int k = 2; // k=2, So 2nd smallest number in the BST
ShowSmall(root, k); //If k=2, OP should be 21
return 0;
}