You are given the root of a binary search tree and an integer k. Return True if the tree has two different nodes whose values add up to k, and False otherwise.
Function Signature
def find_target(root: Optional[TreeNode], k: int) -> bool:
Rules
-
In the examples the tree is written as a level-order list, with
None
marking a missing child. The function receives the root
TreeNode
built from that list; each node has the fields
val
,
left
and
right
.
-
The two nodes must be different. One node cannot be used twice, even when
k
is exactly twice its value.
-
The tree is a valid binary search tree: every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger.
Constraints
-
1 <= number of nodes <= 10^4
-
-10^4 <= Node.val <= 10^4
-
-10^5 <= k <= 10^5
-
root
is a valid binary search tree.
Examples
Input: root = [5, 3, 6, 2, 4, None, 7], k = 9
Output: True
The root is 5, its left child 3 has children 2 and 4, and its right child 6 has a right child 7. Several pairs sum to 9 (2 and 7, 3 and 6, 4 and 5), so the answer is True.
Input: root = [5, 3, 6, 2, 4, None, 7], k = 28
Output: False
The largest sum of two different nodes is 6 + 7 = 13, so no pair can reach 28.
Input: root = [1], k = 2
Output: False
The only node has value 1. Reaching 2 would mean using that node twice, which is not allowed.