Talentd
FleetCode

653. Two Sum IV - Input is a BST

Easy63.7% acceptance8 companies

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:

  • 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
3:19
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# Definition for a binary tree node.
2# class TreeNode:
3# def __init__(self, val=0, left=None, right=None):
4# self.val = val
5# self.left = left
6# self.right = right
7class Solution:
8 def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
9
Starter codePython 3Spaces: 4
Examples
Input
[5,3,6,2,4,null,7]
9
Input
[5,3,6,2,4,null,7]
28
Your code is saved on this device.Solution