struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void inOrderTraversal(TreeNode *n, TreeNode* &pre, TreeNode* &p, TreeNode* &q) {
if (n == NULL) return;
inOrderTraversal(n->left, pre, p, q);
if (pre != NULL && pre->val > n->val) {
if (p == NULL) {
p = pre;
}
q = n;
}
pre = n;
inOrderTraversal(n->right, pre, p, q);
}
void recoverTree(TreeNode *root) {
TreeNode *pre = NULL;
TreeNode *p = NULL;
TreeNode *q = NULL;
inOrderTraversal(root, pre, p, q);
if (p != NULL && q != NULL) {
int tmp = p->val;
p->val = q->val;
q->val = tmp;
}
}