Skip to main content

Two Sum IV - Input is a BST

Problem

Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.

Solution Approach

Expected Time complexity: O(n)O(n)

Click - to see solution code
class Solution {
public:
set<int> s;
bool findTarget(TreeNode* root, int k) {
if (root == nullptr) return false;
int f = k - root->val;
if (s.find(f) != s.end()) {
return true;
} else {
s.insert(root->val);
s.insert(f);
}
bool l = findTarget(root->left, k);
bool r = findTarget(root->right, k);
if (l || r) return true;
return false;
}
};