Recover Binary Search Tree

Medium

Company Tags

You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.

Example 1:

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

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

Example 2:

Input: root = [2,3,1]

Output: [2,1,3]

Constraints:

  • 2 <= The number of nodes in the tree <= 1000.
  • -(2^31) <= Node.val <= ((2^31)-1)

Follow up: A solution using O(n) space is pretty straight-forward. Could you devise a constant O(1) space solution?



Company Tags

Please upgrade to NeetCode Pro to view company tags.

root =