Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
vector<int> nums;
inorder(root, nums);
return findTargetInSortedArray(nums, k);
}
private:
void inorder(TreeNode* node, vector<int>& nums) {
if (!node) return;
inorder(node->left, nums);
nums.push_back(node->val);
inorder(node->right, nums);
}
bool findTargetInSortedArray(vector<int> a, int target) {
for (int i = 0, j = a.size() - 1; i < j;) {
int sum = a[i] + a[j];
if (sum == target) {
return true;
}
else if (sum < target) {
i++;
}
else {
j--;
}
}
return false;
}
};
class BSTIterator {
stack<TreeNode*> s;
TreeNode* node;
bool forward;
public:
BSTIterator(TreeNode *root, bool forward) : node(root), forward(forward) {};
bool hasNext() {
return node != nullptr || !s.empty();
}
int next() {
while (node || !s.empty()) {
if (node) {
s.push(node);
node = forward ? node->left : node->right;
}
else {
node = s.top();
s.pop();
int nextVal = node->val;
node = forward ? node->right : node->left;
return nextVal;
}
}
return -1; // never reach & not necessary
}
};
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
if (!root) return false;
BSTIterator l(root, true);
BSTIterator r(root, false);
for (int i = l.next(), j = r.next(); i < j;) {
int sum = i + j;
if (sum == k) {
return true;
}
else if (sum < k) {
i = l.next();
}
else {
j = r.next();
}
}
return false;
}
};
bool findTarget(TreeNode* root, int k) {
unordered_set<int> set;
return dfs(root, set, k);
}
bool dfs(TreeNode* root, unordered_set<int>& set, int k){
if(root == NULL)return false;
if(set.count(k - root->val))return true;
set.insert(root->val);
return dfs(root->left, set, k) || dfs(root->right, set, k);
}