-
Notifications
You must be signed in to change notification settings - Fork 0
/
50_Kth_small.cpp
59 lines (48 loc) · 1.04 KB
/
50_Kth_small.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
#include <iostream>
#include <stack>
#include <string>
#include <algorithm>
#include <sstream>
#include <queue>
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) {
if(root == nullptr)return 0;
int res;
TreeNode *cur = root;
stack<TreeNode *> s;
while(k && (cur != nullptr || !s.empty())){
while(cur){
s.push(cur);
cur = cur->left;
}
cur = s.top();
res = cur->val;
s.pop();
cout << k << endl;
k--;
cur = cur->right;
}
return res;
}
};
int main()
{
TreeNode N1(3);
TreeNode N2(1);
TreeNode N3(2);
TreeNode N4(4);
N1.left = &N2;
N1.right = &N4;
N2.right = &N3;
Solution s;
cout << s.kthSmallest(&N1,1) << endl;
return 0;
}