Two Sum IV - Input is a BST

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
        5
       / \
      3   6
     / \   \
    2   4   7
Inputroot = [5,3,6,2,4,null,7], k = 9
Outputtrue
The BST contains values 5 and 4, whose sum is 9.
Example 2
        5
       / \
      3   6
     / \   \
    2   4   7
Inputroot = [5,3,6,2,4,null,7], k = 28
Outputfalse
No two elements in the BST sum to 28.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • -10^4 <= Node.val <= 10^4
  • root is guaranteed to be a valid binary search tree.
  • -10^5 <= k <= 10^5

Asked at 8 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate