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 - Input is a BST INPUT Binary Search Tree 5 3 6 2 4 7 root = [5,3,6,2,4,null,7] k = 9 Find two nodes: sum = 9 ALGORITHM (Hash Set) 1 Initialize Hash Set Create empty set for values 2 Traverse BST Visit each node (any order) 3 Check Complement Is (k - node.val) in set? 4 Add to Set Add current value to set Hash Set Progress: 5 3 2 4 At node 6: check 9-6=3 3 found in set! OK Pair Found: 3 + 6 = 9 FINAL RESULT Solution Found in BST 5 3 6 2 4 7 3 + 6 = 9 Target k = 9 Output: true OK - Two sum exists! Key Insight: Using a Hash Set allows O(1) lookup for each node's complement (k - node.val). This transforms the problem from O(n^2) brute force to O(n) time with O(n) space. We traverse the BST once, checking if the complement exists before adding the current value. BST property optional for this approach. TutorialsPoint - Two Sum IV - Input is a BST | Hash Set Approach
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