Two Sum BSTs
Description
null
Solution(javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root1
* @param {TreeNode} root2
* @param {number} target
* @return {boolean}
*/
const twoSumBSTs = function (root1, root2, target) {
const map = {}
const bfs = (node, f) => {
if (!node) {
return
}
let current = [node]
while (current.length > 0) {
const next = []
current.forEach((currentNode) => {
f(currentNode)
if (currentNode.left) {
next.push(currentNode.left)
}
if (currentNode.right) {
next.push(currentNode.right)
}
})
current = next
}
}
bfs(root1, (node) => {
map[node.val] = true
})
let valid = false
bfs(root2, (node) => {
if (map[target - node.val]) {
valid = true
}
})
return valid
}