Skip to the code
cf.
+50 XP

#334 Recover Two Swapped Prices

hard

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. Try to use only O(1) extra memory.

Example 1

Input: root = [5,8,2]
Output: [5,2,8]

8 and 2 traded places. Swapping them back restores the order.

Example 2

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.

Constraints

  • 2 <= number of nodes <= 1000
  • Exactly two values are out of place.

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).