https://www.geeksforgeeks.org/batch/gfg-160-problems/track/tree-gfg-160/problem/find-a-pair-with-given-target-in-bst
class Solution {
public:
bool findTarget(Node *root, int target) {
// your code here.
vector<int > res ;
helper(root , res);
int left =0 ;
int right= res.size() -1;
while(left < right ){
if(res[left] + res[right] == target){
return true;
}else if(res[left] + res[right] < target){
left++;
}else right--;
}
return false;
}
private:
void helper(Node* root , vector<int> & res){
if(!root) return;
helper(root->left , res);
res.push_back(root->data );
helper(root->right , res);
}
};
Time & Space Complexity:
- Time: O(n) – In-order traversal and two-pointer scan.
- Space: O(n) – Extra space for the
nums
array.