# Problem 99: Recover Binary Search Tree

> <https://leetcode.com/problems/recover-binary-search-tree/#/description>

## 思路

* 一个经典的 inorder 模板，可以解决一类 tree 中顺序增加的题目

```java
private void traverse (TreeNode root) {
   if (root == null) return;

   traverse(root.left);
   // Do some business
   traverse(root.right);
}
```

* 这个讲解很好

> <https://discuss.leetcode.com/topic/3988/no-fancy-algorithm-just-simple-and-powerful-in-order-traversal>

```java
// space: O(logn)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode firstNode = null;
    TreeNode secondNode = null;
    TreeNode prevNode = new TreeNode(Integer.MIN_VALUE);

    public void recoverTree(TreeNode root) {
        traverse(root);

        int tmp = firstNode.val;
        firstNode.val = secondNode.val;
        secondNode.val = tmp;
    }

    private void traverse(TreeNode root) {
        if (root == null) return;

        traverse(root.left);

        if (firstNode == null && prevNode.val >= root.val) {
            firstNode = prevNode;
        }
        if (firstNode != null && prevNode.val >= root.val) {
            secondNode = root;
        }
        prevNode = root;

        traverse(root.right);
    }
}
```

## Follow Up

* Morris 算法可以用 O(1) 来解决 tree 的遍历


---

# 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://liuyang89116.gitbook.io/my-leetcode-book/chapter_3_binary_tree_bfs-_dfs/traversals/problem-94-binary-tree-inorder-traversal/problem-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.
