# 99 Recover Binary Search Tree

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

Recover the tree without changing its structure.

**Note:** A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

**The Idea:** Run an in order traversal through the tree. Collect the nodes. It will always follow that there are two nodes within the container that need to be swapped. Find these nodes and swap their values.

**Complexity:** O(n) time and O(n) space

```cpp
void inOrderTraverse(TreeNode *root, vector<TreeNode*> &nodes) {
    if (root) {
        inOrderTraverse(root->left, nodes);
        nodes.push_back(root);
        inOrderTraverse(root->right, nodes);
    }
}

void my_swap(TreeNode *r1, TreeNode *r2) {
    int temp = r1->val;
    r1->val = r2->val;
    r2->val = temp;
}

pair<int, int> findMisplacedElements(vector<TreeNode*> nodes) {
    assert(nodes.size() > 1);
    for (int i = nodes.size() - 1; i > 0; i--) {
        if (nodes[i]->val < nodes[i - 1]->val) {
            int j = i - 1;
            while (j >= 0 && nodes[i]->val < nodes[j]->val)
                j--;
            return { i, j + 1 };
        }
    }
}

void recoverTree(TreeNode* root) {
    static vector<TreeNode*> nodes;
    nodes.clear();
    inOrderTraverse(root, nodes);
    pair<int, int> misplaced = findMisplacedElements(nodes);
    my_swap(nodes[misplaced.first], nodes[misplaced.second]);
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/99-recover-binary-search-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
