653. Two Sum IV - Input is a BST
Problem
Tags: Hash Table
, Two Pointers
, Tree
, Depth-First Search
, Breadth-First Search
, Binary Search Tree
, Binary Tree
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, 10^4]
. -10^4 <= Node.val <= 10^4
root
is guaranteed to be a valid binary search tree.-10^5 <= k <= 10^5
Code
JS
// 653. Two Sum IV - Input is a BST (6/10/53748)
// Runtime: 187 ms (10.98%) Memory: 48.11 MB (94.88%)
/**
* 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}
*/
function findTarget(root, k) {
const set = new Set();
const queue = [root];
while (queue.length) {
const node = queue.shift();
if (set.has(node.val)) return true;
set.add(k - node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return false;
}