Skip to main content
LeetCode 99, Medium. Topics: Tree, Depth-First Search, Binary Search Tree, Binary Tree. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 14 parametrized pytest cases, and a playground notebook:

Problem

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.

Examples

Example 1
Example 2

Constraints

  • The number of nodes in the tree is in the range [2, 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?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026