forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
kth_smallest.cpp
91 lines (82 loc) · 2.04 KB
/
kth_smallest.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
/*
* Given a binary search tree, find the kth smallest element in it.
* Assumption: k is always valid i.e. 1 <= k <= total number of nodes in BST
*
* 8
* / \
* / \
* 4 10
* / \ / \
* / \ / \
* 2 6 9 12
* k = 2, answer: 4
* k = 7, answer: 12
*/
#include <iostream>
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int d):
data{d}, left{nullptr}, right{nullptr} { }
};
int countNodes(TreeNode* root)
{
if (root == nullptr) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
int kthSmallest(TreeNode* root, int k)
{
int count = countNodes(root->left);
if (k <= count && root->left) {
return kthSmallest(root->left, k);
} else if ( k > count + 1 && root->right) {
return kthSmallest(root->right, k - count - 1);
}
return root->data;
}
void insertNode(TreeNode* &root, int d)
{
if (!root) {
TreeNode* newNode = new TreeNode(d);
root = newNode;
return;
}
if (root->data >= d) {
insertNode(root->left, d);
}
else {
insertNode(root->right, d);
}
}
void inorder(TreeNode* root)
{
if (root) {
inorder(root->left);
std::cout << root->data << " ";
inorder(root->right);
}
}
int main()
{
TreeNode* root = nullptr;
insertNode(root, 8);
insertNode(root, 4);
insertNode(root, 10);
insertNode(root, 2);
insertNode(root, 6);
insertNode(root, 9);
insertNode(root, 12);
std::cout << "Inorder traversal of tree:" << std::endl;
inorder(root);
std::cout << std::endl;
std::cout << "2nd smallest element in tree: " << kthSmallest(root, 2)
<< std::endl;
std::cout << "4th smallest element in tree: " << kthSmallest(root, 4)
<< std::endl;
std::cout << "7th smallest element in tree: " << kthSmallest(root, 7)
<< std::endl;
return 0;
}