Skip to content

Commit 9b2c39f

Browse files
authored
Create two-sum-iv-input-is-a-bst.cpp
1 parent 5946bfb commit 9b2c39f

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

C++/two-sum-iv-input-is-a-bst.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
14+
class Solution {
15+
public:
16+
bool findTarget(TreeNode* root, int k) {
17+
if (!root) {
18+
return false;
19+
}
20+
BSTIterator left(root, true), right(root, false);
21+
while (*left < *right) {
22+
if (*left + *right == k) {
23+
return true;
24+
} else if (*left + *right < k) {
25+
++left;
26+
} else {
27+
++right;
28+
}
29+
}
30+
return false;
31+
}
32+
33+
private:
34+
class BSTIterator {
35+
public:
36+
BSTIterator(TreeNode *root, bool forward) :
37+
node_(root),
38+
forward_(forward) {
39+
++(*this);
40+
};
41+
42+
int operator*() {
43+
return cur_;
44+
}
45+
46+
void operator++() {
47+
while (node_ || !s_.empty()) {
48+
if (node_) {
49+
s_.emplace(node_);
50+
node_ = forward_ ? node_->left : node_->right;
51+
} else {
52+
node_ = s_.top();
53+
s_.pop();
54+
cur_ = node_->val;
55+
node_ = forward_ ? node_->right : node_->left;
56+
break;
57+
}
58+
}
59+
}
60+
61+
private:
62+
TreeNode* node_;
63+
bool forward_;
64+
stack<TreeNode*> s_;
65+
int cur_;
66+
};
67+
};

0 commit comments

Comments
 (0)