Two Sum IV - Input is a BST

Easy

Description

Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum equals the given target.

Examples

Input:root = [5,3,6,2,4,null,7], k = 9
Output:true
Explanation:

2 + 7 = 9.

Input:root = [5,3,6,2,4,null,7], k = 28
Output:false
Explanation:

No two nodes in the BST sum to 28. The largest possible pair sum is 4+7=11.

Input:root = [2,1,3], k = 4
Output:true
Explanation:

1 + 3 = 4. This example demonstrates the algorithm working on a minimal BST with only 3 nodes, where the two nodes that sum to the target are the leftmost and rightmost nodes in the tree.

Constraints

  • 1 ≤ nodes ≤ 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!