Easy
Given the root
of a binary search tree and an integer k
, return true
if there exist two elements in the BST such that their sum is equal to k
, or false
otherwise.
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:
[1, 104]
.-104 <= Node.val <= 104
root
is guaranteed to be a valid binary search tree.-105 <= k <= 105
import com_github_leetcode.TreeNode
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun findTarget(root: TreeNode?, k: Int): Boolean {
if (root == null) {
return false
}
val res: MutableList<Int> = ArrayList()
inOrder(res, root)
var i = 0
var j = res.size - 1
while (i < j) {
val val1 = res[i]
val val2 = res[j]
if (val1 + val2 == k) {
return true
} else if (val1 + val2 < k) {
i++
} else {
j--
}
}
return false
}
private fun inOrder(res: MutableList<Int>, root: TreeNode?) {
if (root == null) {
return
}
inOrder(res, root.left)
res.add(root.`val`)
inOrder(res, root.right)
}
}