Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void recoverTree(TreeNode *root) {
TreeNode* pre_node = NULL;
stack<TreeNode*>StackNode;
TreeNode*cur_node = root;
TreeNode*misnode1 = NULL;
TreeNode*misnode2 = NULL;
while (1)
{
while (cur_node)
{
StackNode.push(cur_node);
cur_node = cur_node->left;
}
if (StackNode.empty())
break;
cur_node = StackNode.top();
StackNode.pop();
if (pre_node!=NULL&&pre_node->val>cur_node->val)
{
if (!misnode1){
misnode1 = pre_node;
misnode2 = cur_node;
}
else
misnode2 = cur_node;
}
pre_node = cur_node;
cur_node = cur_node->right;
}
if (misnode1&&misnode2)
swap(misnode1->val,misnode2->val);
}