Given the root of a binary search tree and an integer k, return true if there exist two distinct elements in the BST such that their sum equals k, or false otherwise.

This problem leverages the unique properties of Binary Search Trees where elements are organized in a sorted manner. The challenge is to efficiently find two nodes whose values sum to the target value k.

Note: You cannot use the same element twice, and the two elements must be different nodes in the tree.

Input & Output

example_1.py โ€” Basic BST
$ Input: root = [5,3,6,2,4,null,7], k = 9
โ€บ Output: true
๐Ÿ’ก Note: We can find two nodes with values 2 and 7 that sum to 9 (2 + 7 = 9). These are distinct nodes in the BST.
example_2.py โ€” No Valid Pair
$ Input: root = [5,3,6,2,4,null,7], k = 28
โ€บ Output: false
๐Ÿ’ก Note: No two distinct nodes in the BST have values that sum to 28. The maximum possible sum is 6 + 7 = 13.
example_3.py โ€” Single Node
$ Input: root = [2], k = 4
โ€บ Output: false
๐Ÿ’ก Note: The BST contains only one node with value 2. We need two distinct nodes, so it's impossible to find a pair that sums to 4.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -104 โ‰ค Node.val โ‰ค 104
  • -105 โ‰ค k โ‰ค 105
  • The tree is guaranteed to be a valid binary search tree

Visualization

Tap to expand
Two Sum IV - BST Hash Set Approach536247Hash Set Journey (k=9)Step 1: Visit node 5โ€ข Need: 9-5=4, Set: {} โ†’ Add 5Step 2: Visit node 3โ€ข Need: 9-3=6, Set: {5} โ†’ Add 3Step 3: Visit node 2โ€ข Need: 9-2=7, Set: {5,3} โ†’ Add 2Step 4: Visit node 7 โ†’ Found!When we reach node 7, we need 9-7=2, which exists in our set! โœ“
Understanding the Visualization
1
Start with empty memory
Begin traversal with empty hash set to remember values
2
Check each node
For node with value v, check if (k-v) was seen before
3
Remember current value
Add current node's value to hash set for future lookups
4
Continue until found
Repeat process until pair found or tree fully traversed
Key Takeaway
๐ŸŽฏ Key Insight: Hash sets provide O(1) complement lookup, making single-pass traversal optimal for this two-sum variant on tree structures!
Asked in
Amazon 42 Google 35 Microsoft 28 Meta 22
52.0K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen