# LeetCode | Recover Binary Search Tree（恢复二叉搜索树）

wo 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?

1、两次查找的时候，都是当前值比前一个小的时候，但第一次取前一个值，第二个取后一个值。

2、如果需要交换的两个点正好相邻呢？所有当big被赋值的时候，small也要被赋值！

``````class Solution {
public:
void recoverTree(TreeNode *root) {
if(root == NULL)
return ;
InOrderTraverse(root);
}
void InOrderTraverse(TreeNode *root){
stack<TreeNode *> S;
TreeNode *p = root;
vector<int> num;
TreeNode *tmp = NULL;
TreeNode *big = NULL;
TreeNode *small = NULL;
bool flag = false;
while(p || !S.empty()){
if(p){
S.push(p);
p = p->left;
}else{
p = S.top();
S.pop();
if(tmp == NULL){
tmp = p;
p = p->right;
continue;
}
if(!flag){
if(tmp->val > p->val){
big = tmp;
small = p;
flag = true;
}
}else{
if(tmp->val > p->val){
small = p;
break;
}
}
tmp = p;
p = p->right;
}
}
int a = big->val;
big->val = small->val;
small->val = a;
}
};
``````