Learned from http://www.cnblogs.com/tgkx1054/archive/2013/05/24/3096830.html. Do the inorder traversal of the tree, and we will always get root->val less than pre->val. If root->val > pre->val, mistake is found.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* pre;
TreeNode* p,*q;
void recoverTree(TreeNode* root) {
p=q=pre=NULL;
inorder(root);
swap(p->val,q->val);
}
void inorder(TreeNode* root)
{
if(!root)
return;
if(root->left)
inorder(root->left);
if(pre&&pre->val>root->val)
{
if(!p)
p=pre;
q=root;
}
pre=root;
if(root->right)
inorder(root->right);
}
};