← DiffPush

Two Sum IV — Pair in a BST

Standard Bar Binary Search Trees · Practice Problems O(n) · O(h)

The Two-Clamp Balance Check

A treasury terminal holds account balances in a sorted tree and must verify whether any two distinct accounts can settle an invoice exactly — their balances summing to the target. Instead of dumping the tree into a list, the terminal clamps from both ends simultaneously: the smallest candidate climbs up while the largest climbs down, adjusting whichever side overshoots until they meet or cross.

Input: A binary search tree as a level-order array (null marks a missing child) and an integer k — the target sum.

Output: Return true if two distinct nodes hold values summing to k, otherwise false.

Constraints

Examples

Example 1

Input: {"tree":[5,3,6,2,4,null,7],"k":9}
Output: true
The pair 2 + 7 (or 3 + 6) hits the target exactly.

Example 2

Input: {"tree":[5,3,6,2,4,null,7],"k":28}
Output: false
The two largest values 6 and 7 already sum to only 13.

Solve this in your browser →

Also on LeetCode ↗