class Solution {
public:
void recoverTree(TreeNode *root) {
TreeNode *cur=root,*pre=nullptr;
TreeNode *first=nullptr,*second=nullptr,*parent=nullptr;
while(cur)
{
if(!cur->left)
{
if(parent && parent->val > cur->val)
{
if (!first)
first=parent;
second=cur;
}
parent=cur;
cur=cur->right;
}
else
{
pre=cur->left;
while(pre->right != nullptr && pre->right != cur)
pre=pre->right;
if(pre->right == nullptr)
{
pre->right=cur;
cur=cur->left;
}
else
{
pre->right=nullptr;
if(parent && parent->val > cur->val)
{
if (!first)
first=parent;
second=cur;
}
parent=cur;
cur=cur->right;
}
}
}
if (first && second) swap(first->val, second->val);
}
};