Skip to the code
cf.
+25 XP

#332 Pair of Prices for a Budget

medium

A gift-bundle feature wants to know whether two different products together cost exactly the shopper's budget. Prices are stored in a binary search tree with unique values.

Write hasPair(root, budget) that returns true if two different nodes have values that add up to budget, and false otherwise. Aim for O(h) extra memory, where h is the tree's height.

Example 1

Input: root = [5,3,8,1,4,7,9], budget = 12
Output: true

3 + 9 = 12 (and 4 + 8 = 12).

Example 2

Input: root = [5,3,8,1,4,7,9], budget = 2
Output: false

The two cheapest prices already add up to 4.

Constraints

  • 0 <= number of prices <= 10000
  • -10^5 <= price, budget <= 10^5

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).