AlgoFrames

Recover a swapped BST

Challenge · Write code · about 20 min

The keys of two nodes of a BST were swapped by mistake. Swap them back and return the root. Do not change the shape of the tree. If the tree is already valid, return it unchanged.

Example 1

Input:

[[1,3,null,null,2]]

Output:

[3,1,null,null,2]

1 and 3 were swapped.

Example 2

Input:

[[3,1,4,null,null,2]]

Output:

[2,1,4,null,null,3]

3 and 2 were swapped.

Constraints

  • 1 ≤ number of nodes ≤ 1,000
  • Keys are distinct integers with -1,000 ≤ key ≤ 1,000
  • At most one pair of keys is swapped; the tree is given in level order, null marks a missing child

Learn the idea first: Validating a BST and the in-order property, a visual lesson.

More Validating a BST and the in-order property problems