99. Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input:
 [1,3,null,null,2]

   1
  /
 3
  \
   2


Output:
 [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Follow up:

  • A solution using O(n) space is pretty straight forward.

  • Could you devise a constant space solution?

Thoughts:

  1. In-order traversal + first, sec, prev node global record

  2. Morris traversal to save space

Code 1 T: O(n); S: O(n) due to call stack space:

Code 2: T:O(n); S: O(1)

Last updated

Was this helpful?