-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclosest-binary-search-tree-value-ii.cpp
65 lines (59 loc) · 1.93 KB
/
closest-binary-search-tree-value-ii.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
/**
* 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:
// ????????????AC,??????https://leetcode.com/submissions/detail/264400911/
// ????https://www.cnblogs.com/grandyang/p/5247398.html
// smaller?????target?????larger?????target????
// ????????????
vector<int> closestKValues(TreeNode* root, double target, int k) {
vector<int> res;
stack<TreeNode*> smaller,larger;
while(root){
// if(root) cout<<root->val<<endl;
if(root->val<target){
smaller.push(root);
root=root->right;
}
else{
larger.push(root);
root=root->left;
}
}
while(--k>=0){ // ???res???????????smaller?larger?????smaller?larger??????????
if(smaller.empty() || (!larger.empty() && larger.top()->val-target<target-smaller.top()->val)){
res.push_back(larger.top()->val);
next_larger(larger);
}
else{
res.push_back(smaller.top()->val);
next_smaller(smaller);
}
}
return res;
}
// ?????smaller.top()??????
void next_smaller(stack<TreeNode*> &smaller){ // ?????????????????????????????????
auto root=smaller.top();
smaller.pop();
if(root->left){ // ?????????????????????????
smaller.push(root->left);
while(smaller.top()->right) smaller.push(smaller.top()->right);
}
}
void next_larger(stack<TreeNode*> &larger){
auto root=larger.top();
larger.pop();
if(root->right){
larger.push(root->right);
while(larger.top()->left) larger.push(larger.top()->left);
}
}
};