Date:2019-3-23
题目地址:https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst/submissions/
给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。
案例 1:
输入: 5 / \ 3 6 / \ \ 2 4 7
Target = 9
输出: True
案例 2:
输入: 5 / \ 3 6 / \ \ 2 4 7
Target = 28
输出: False
解法分析:
看到是二叉树,我们就会想到它会有left和right,把他的左边和右边的数字写在一个储存对象内,然后用变量去存下来 目标值减去当前值的另外一个数,如果这个数与其相等,那么直接返回 true,如果全部不相等,则为 false,
因为二叉树没有办法获取到它的父级,所以我们单独领出来一个储存对象给它,之所以用for不使用forEach是因为forEach没办法直接return
const findTarget = (root, k) => {
if(root === null) {
return false
}
let p = root
let bufferDict = {}
let queue = [p]
for (let i = 0; i < queue.length; i++) {
p = queue[i]
p.left && queue.push(p.left)
p.right && queue.push(p.right)
let otherNum = k - p.val
if(bufferDict[otherNum]) {
return true
} else {
bufferDict[p.val] = true
}
}
return false
}