Given the root of a binary search tree and an integer k, return trueif there exist two elements in the BST such that their sum is equal tok, orfalseotherwise.
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
Solutions
Solution 1
1 2 3 4 5 6 7 8 9101112131415161718
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:deffindTarget(self,root:Optional[TreeNode],k:int)->bool:defdfs(root):ifrootisNone:returnFalseifk-root.valinvis:returnTruevis.add(root.val)returndfs(root.left)ordfs(root.right)vis=set()returndfs(root)
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcfindTarget(root*TreeNode,kint)bool{vis:=map[int]bool{}vardfsfunc(*TreeNode)booldfs=func(root*TreeNode)bool{ifroot==nil{returnfalse}ifvis[k-root.Val]{returntrue}vis[root.Val]=truereturndfs(root.Left)||dfs(root.Right)}returndfs(root)}