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. A store can hold up to 100,000 prices, so checking every pair is far too slow. Aim for O(h) extra memory, where h is the tree's height.
Input: root = [5,3,8,1,4,7,9], budget = 12 Output: true
3 + 9 = 12 (and 4 + 8 = 12).
Input: root = [5,3,8,1,4,7,9], budget = 2 Output: false
The two cheapest prices already add up to 4.
0 <= number of prices <= 10^53000 levels deep.-10^5 <= price, budget <= 10^5Trees 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.
Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #332 Pair of Prices for a Budget. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.