Community Problem

Two Sum IV - Input is a BST

Difficulty: Easy

Decide whether two distinct BST nodes sum to a target, ideally in O(n) time and O(h) extra space.

Two Sum IV - Input is a BST

Decide whether two distinct BST nodes sum to a target, ideally in O(n) time and O(h) extra space.

EASY
Free
trees
bst
two-pointers
dfs
owentoure

By @owentoure

February 28, 2026

·

Updated May 20, 2026

418 views

9

Rate

I had a candidate freeze on this one because they pattern-matched to Two Sum on an array and reached for a hash set, ignoring the BST structure entirely. That works (it is the canonical answer most people give), but the follow-up question is the actual interview signal: can you solve it in O(h) extra space using ordered traversal and the two-pointers idea? That second solution is what the practice catalog skipped, so it is what this entry is really about.

Two Sum IV - Input is a BST

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

Examples

Example 1:

  • Input: root = [5, 3, 6, 2, 4, null, 7], k = 9
  • Output: true
  • Explanation: Nodes 2 and 7 sum to 9.

Example 2:

  • Input: root = [5, 3, 6, 2, 4, null, 7], k = 28
  • Output: false
  • Explanation: No two values in the tree sum to 28.

Example 3:

  • Input: root = [2, 1, 3], k = 4
  • Output: true
  • Explanation: Nodes 1 and 3 sum to 4.

Example 4:

  • Input: root = [1], k = 2
  • Output: false
  • Explanation: A single node cannot pair with itself; the problem requires two distinct nodes.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • -10^4 <= Node.val <= 10^4.
  • The tree is guaranteed to be a valid BST.
  • -10^5 <= k <= 10^5.

Follow-up

The hash-set solution is O(n) time and O(n) space. Can you keep O(n) time but cut space to O(h)? Hint: in-order traversal of a BST yields a sorted sequence, and Two Sum on a sorted sequence has a two-pointer answer.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems