-
Notifications
You must be signed in to change notification settings - Fork 11
/
Day-036.cpp
47 lines (47 loc) · 1.14 KB
/
Day-036.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
/**
* 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 {
int ans;
bool isAnsFound;
int tempCounter;
void getans(TreeNode* root , int k){
if(isAnsFound){
return;
}
if(root->right!=nullptr){
getans(root->right , k);
}
tempCounter++;
if(k==tempCounter){
isAnsFound = true;
ans = root -> val;
tempCounter++;
return;
}
if(!isAnsFound && root->left != nullptr){
getans(root->left , k);
}
if(k==tempCounter){
isAnsFound = true;
ans = root -> val;
return;
}
}
public:
int kthSmallest(TreeNode* root) {
tempCounter =0;
ans = -1;
isAnsFound = false;
getans(root , 2);
return ans;
}
};