-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path230.cpp
More file actions
executable file
·53 lines (51 loc) · 1.46 KB
/
230.cpp
File metadata and controls
executable file
·53 lines (51 loc) · 1.46 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
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 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 {
public:
int numth;
int ans;
bool flag;
vector<int> concact(TreeNode* current){
if (current->left == NULL && current->right == NULL){
vector<int> tmp;
tmp.push_back(current->val);
if (tmp.size() >= numth){
flag = true;
ans = tmp[numth-1];
return tmp;
}
return current;
}
vector<int> tmp;
vector<int> left;
vector<int> right;
if (flag) return left;
if (current->left != NULL) left = concat(current->left);
if (flag) return left;
if (current->right != NULL) right = concat(current->right);
if (flag) return left;
left.push_back(current->val);
left.insert(left.end(),right.begin(),right.end());
if (left.size() >= numth){
flag = true;
ans = left[numth-1];
return left;
}
return left;
}
int kthSmallest(TreeNode* root, int k) {
numth = k;
flag = false;
concat(root);
return ans;
}
};