-
Notifications
You must be signed in to change notification settings - Fork 0
/
653.hpp
68 lines (59 loc) · 1.4 KB
/
653.hpp
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
66
67
68
#ifndef LEETCODE_653_HPP
#define LEETCODE_653_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
#include "../common/leetcode.hpp"
using namespace std;
class BSTIterator {
public:
BSTIterator(TreeNode *node, bool forward) : node(node), forward(forward) { (*this)++; }
int operator*() {
return cur;
}
void operator++(int) {
while (node || !depth.empty()) {
if (node) {
depth.emplace(node);
node = forward ? node->left : node->right;
} else {
node = depth.top();
depth.pop();
cur = node->val;
node = forward ? node->right : node->left;
break;
}
}
}
private:
stack<TreeNode *> depth;
TreeNode *node;
bool forward;
int cur;
};
class Solution {
public:
bool findTarget(TreeNode *root, int k) {
if (root == nullptr)
return false;
BSTIterator l(root, true);
BSTIterator r(root, false);
while (*l < *r) {
if (*l + *r == k)
return true;
else if (*l + *r < k)
l++;
else
r++;
}
return false;
}
};
#endif //LEETCODE_653_HPP