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:
Example 2:
C++
bool findTarget(TreeNode* root, int k) {
vector<int> nums;
stack<TreeNode*> nodes;
bool res = false;
while(!nodes.empty()||root)
{
if(root)
{
nodes.push(root);
root = root->left;
}
else
{
root = nodes.top();
nodes.pop();
nums.push_back(root->val);
root = root->right;
}
}
int left = 0;
int right = nums.size()-1;
while(left < right)
{
if(nums[left] + nums[right] == k)
{
res = true;
break;
}
else if(nums[left] + nums[right] < k)
++left;
else
--right;
}
return res;
}