-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path230 Kth Smallest Element in a BST.cpp
More file actions
41 lines (38 loc) · 1.04 KB
/
230 Kth Smallest Element in a BST.cpp
File metadata and controls
41 lines (38 loc) · 1.04 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
static int fastio=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
/**
* 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 {
// check left->root->right (inorder traversal)
int find(TreeNode* root, int& k) {
if (root) {
int x = find(root->left, k);
if(!k)
return x;
else{
if(!--k)
return root->val;
else
return find(root->right,k);
}
}
// return !k ? x : !--k ? root->val : find(root->right, k);
return -1;
}
public:
int kthSmallest(TreeNode* root, int k) {
return find(root, k);
}
};