🎉 One-stop destination for all your technical interview Preparation 🎉
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.
class Solution{
public:
unordered_set<int> s;
bool findTarget(TreeNode *root, int k){
if (!root) return false;
if (s.count(k - root->val)) return true;
s.insert(root->val);
return findTarget(root->left, k) || findTarget(root->right, k);
}
};
bool findTarget(TreeNode* root, int k) {
vector<int> nums;
inorder(root, nums);
for(int i = 0, j = nums.size()-1; i<j;){
if(nums[i] + nums[j] == k)return true;
(nums[i] + nums[j] < k)? i++ : j--;
}
return false;
}
void inorder(TreeNode* root, vector<int>& nums){
if(root == NULL)return;
inorder(root->left, nums);
nums.push_back(root->val);
inorder(root->right, nums);
}
h
is the height of the tree, which is logn
at best case, and n
at worst case. bool findTarget(TreeNode* root, int k) {
return dfs(root, root, k);
}
bool dfs(TreeNode* root, TreeNode* cur, int k){
if(cur == NULL)return false;
return search(root, cur, k - cur->val) || dfs(root, cur->left, k) || dfs(root, cur->right, k);
}
bool search(TreeNode* root, TreeNode *cur, int value){
if(root == NULL)return false;
return (root->val == value) && (root != cur)
|| (root->val < value) && search(root->right, cur, value)
|| (root->val > value) && search(root->left, cur, value);
}