653. Two Sum IV - Input is a BST
Two Sum IV - Input is a BST
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.
Example 1:

Input: root = [5,3,6,2,4,null,7], k = 9 Output: true
Example 2:

Input: root = [5,3,6,2,4,null,7], k = 28 Output: false
Constraints:
- The number of nodes in the tree is in the range
[1, 104]
. -104 <= Node.val <= 104
root
is guaranteed to be a valid binary search tree.-105 <= k <= 105
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {boolean}
*/
var findTarget = function(root, k) {
let set = new Set();
return helper(root, k, set);
};
let helper = function(root, k, set){
if(root==null){
return false;
}
if(set.has(k-root.val)){
return true;
}
set.add(root.val);
return (helper(root.left, k, set) || helper(root.right, k, set));
}
That’s all folks! In this post, we solved LeetCode problem #653. Two Sum IV - Input is a BST
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to solve leetcode questions & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment