-
Notifications
You must be signed in to change notification settings - Fork 0
/
kth_smallest_element_in_bst.cpp
104 lines (87 loc) · 2.38 KB
/
kth_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
99
100
101
102
103
104
// https://leetcode.com/problems/kth-smallest-element-in-a-bst/
// May 05, 2016
#include <iostream>
#include <stack>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL), right(NULL){}
};
class Solution {
public:
int kthSmallest(TreeNode* root, int k)
{
TreeNode* currentNode = root;
int kth_val;
int elem_index = 0;
bool found = false;
stack<TreeNode*> stk;
while ((currentNode != NULL) && (!found))
{
// Keep going left and pushing into stack
while (currentNode != NULL)
{
stk.push(currentNode);
currentNode = currentNode->left;
}
while (!stk.empty())
{
currentNode = stk.top();
stk.pop();
++elem_index;
if (elem_index == k)
{
kth_val = currentNode->val;
found = true;;
break;
}
// If right subtree is present for the currentNode, then we should traverse the right subtree before traversing
// rest of the elements in the stack i.e. elements which should be after in the in-order traversal.
currentNode = currentNode->right;
if (currentNode != NULL)
{
break;
}
}
}
// empty the stack
while (!stk.empty())
{
stk.pop();
}
return kth_val;
}
};
TreeNode* create_tree()
{
TreeNode* node1 = new TreeNode(1);
TreeNode* node2 = new TreeNode(2);
TreeNode* node3 = new TreeNode(3);
TreeNode* node4 = new TreeNode(4);
TreeNode* node5 = new TreeNode(5);
TreeNode* node6 = new TreeNode(6);
node2->left = node1;
node2->right = node4;
node4->left = node3;
node5->left = node2;
node5->right = node6;
return node5;
}
int main(int argc, char* argv[])
{
TreeNode* root = create_tree();
Solution sln;
for (int k = 1; k != 7; ++k)
{
int kth_val = sln.kthSmallest(root, k);
cout << "elem #" << k << " : " << kth_val << endl;
}
return 0;
}
/**
https://en.wikipedia.org/wiki/Tree_traversal#In-order
Here the iterative in-order code is more concise than mine.
*/