Determine whether a binary search tree contains two distinct nodes whose values add up to a target.
Two Sum IV
gfgTwo Sum IV - Input is a BST
You are given the root of a binary search tree and an integer k. Determine whether there exist two distinct nodes in the tree whose values sum to k.
Because the structure is a BST, you may use its ordering properties, but the task only requires deciding whether such a pair exists.
Return true if a valid pair exists, otherwise return false.
Notes
- The two nodes must be different nodes, even if their values are the same.
- The tree may be empty.
- Node values are integers and can be positive, negative, or zero.
Input Format
- The input is a binary search tree rooted at
root. - A target integer
kis given alongside the tree.
Output Format
- Return a boolean value:
trueif there exist two distinct nodes with values summing tokfalseotherwise
Constraints
- The tree can be empty.
- You must use two distinct nodes.
- Values may repeat only if they appear in different nodes.
- The tree satisfies the BST property.
Example 1
Input
root = [5,3,6,2,4,null,7], k = 9
Output
true
Explanation
The nodes with values 5 and 4 sum to 9.
Example 2
Input
root = [5,3,6,2,4,null,7], k = 28
Output
false
Explanation
No pair of distinct nodes adds up to 28.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.