-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathkth_smallest_bst.cpp
104 lines (85 loc) · 2.25 KB
/
kth_smallest_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
// /**
// * Definition for a binary tree node.
// * struct TreeNode {
// * int val;
// * TreeNode *left;
// * TreeNode *right;
// * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
// * };
// */
// class Solution {
// public:
// vector<int> result;
// void traversal(TreeNode *root){
// if(!root) return;
// traversal(root->left);
// result.push_back(root->val);
// traversal(root->right);
// }
// int kthSmallest(TreeNode* root, int k) {
// if(!root) return 0;
// traversal(root);
// int ans = *(result.begin() + k - 1);
// cout<<ans;
// return ans;
// }
// };
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
void helper(TreeNode *root, int k, int &count, int &ans) {
if(!root) return;
if(root->left) {
helper(root->left, k, count, ans);
}
count++;
if(count == k) {
ans = root->val;
return;
}
if(root->right) {
helper(root->right, k, count, ans);
}
}
public:
//recursive
int kthSmallest(TreeNode* root, int k) {
if(root == nullptr) {
return -1;
}
int count = 0, ans = -1;
helper(root, k, count, ans);
return ans;
}
//iterative
int kthSmallest(TreeNode* root, int k) {
if(root == nullptr) {
return -1;
}
stack<TreeNode *> st;
while(root or !st.empty()) {
if(root) {
st.push(root);
root = root->left;
}
else {
root = st.top();
st.pop();
if(--k == 0) {
return root->val;
}
root = root->right;
}
}
return -1;
}
};