A pricing service keeps prices in a binary search tree with unique values. A bad migration swapped the values of exactly two nodes, so the tree no longer follows the search tree rule. The shape of the tree is still correct.
Write recoverPrices(root) that swaps the two wrong values back, changing the tree in place. Don't change the shape. The tree can hold up to 100,000 prices, so trying every pair of nodes is far too slow. Try to use only O(1) extra memory.
Input: root = [5,8,2] Output: [5,2,8]
8 and 2 traded places. Swapping them back restores the order.
Input: root = [10,5,15,2,12,7,20] Output: [10,5,15,2,7,12,20]
Inorder reads 2, 5, 12, 10, 7, 15, 20; 12 and 7 are the swapped pair.
2 <= number of nodes <= 10^53000 levels deep.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.
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 #334 Recover Two Swapped Prices. 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.