Skip to main content
Back to problems
Leetcode
Medium
Trees
Hash Maps
Ordered Structures
Google
Two Sum IV - Input is a BST

Determine whether a binary search tree contains two distinct nodes whose values add up to a target.

Acceptance 100%
Also Available On
Other platform versions and source mappings for the same problem.

Two Sum IV

gfg
Problem Statement

Two 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 k is given alongside the tree.

Output Format

  • Return a boolean value:
    • true if there exist two distinct nodes with values summing to k
    • false otherwise

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.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.