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 distinct nodes whose values add up to k. Pattern focus: BST Search. The BST property helps you search the value space efficiently while avoiding duplicate node usage.

Input Format

root = binary tree root, k = target sum

Output Format

true if two distinct nodes sum to k

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^9 <= node values <= 10^9
  • root and k must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

root = [5,3,6,2,4,null,7]
k = 9

Output:

true

Explanation:

2 + 7 = 9, so a valid pair exists.

Example 2:

Input:

root = [5,3,6,2,4,null,7]
k = 28

Output:

false

Explanation:

No two distinct nodes add up to 28.

Loading...
Two Sum IV - Input is a BST - Binary Search Tree