Find a pair with given target in BST

medium

Given the root of a binary search tree and an integer target, return true if there exist two different nodes in the BST whose values sum to target, and false otherwise.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

This is two-sum — think about how you solve it on an array.
A BST's inorder traversal gives you the values already sorted.
On a sorted array, use two pointers from both ends and move based on the sum.

Common doubts

Both are O(n) time, but the two-pointer sweep uses O(1) extra beyond the array and leans on the BST's natural ordering.
No — it works on any binary tree, since it only checks complements. That's its advantage and why it's the 'brute' baseline here.
Keep the two pointers strictly apart (i < j); the hash-set version only checks against previously-seen nodes.

Interview follow-ups

Walk one BST ascending and the other descending in lockstep — the two-pointer idea across two iterators.
Return the two values at the pointers (or the node and its complement) when the sum matches.

Fun facts

  • This is LeetCode 653 (Two Sum IV) — the tree flavour of the most-asked array problem.
  • The two-pointer sweep is the same skeleton used to merge two sorted BSTs.

Asked at

AmazonMicrosoftFacebook
Frequently Sometimes Occasionally
Example 1
Input: root = [5, 3, 6, 2, 4, null, 7], target = 9
Output: true
2 + 7 = 9 (also 5 + 4).
Example 2
Input: root = [5, 3, 6, 2, 4, null, 7], target = 28
Output: false
No two distinct node values sum to 28.
Constraints

- The number of nodes is in the range [1, 10^4] - -10^5 <= Node.val <= 10^5 - -2 * 10^5 <= target <= 2 * 10^5 - All Node.val are unique

Solve this problem →