Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Solution:
void preorder(TreeNode *root, TreeNode*& pre, TreeNode*& t1, TreeNode*& t2)
{
if(!root)
return;
if(root->left)
preorder(root->left, pre, t1, t2);
if(pre&&pre->val>root->val)
{
t2 = root;
if(!t1)
t1 = pre;
}
pre = root;
if(root->right)
preorder(root->right, pre, t1, t2);
}
void recoverTree(TreeNode *root) {
if(!root)
return;
TreeNode* tmp1 = NULL;
TreeNode* tmp2 = NULL;
TreeNode* pre = NULL;
preorder(root, pre, tmp1, tmp2);
if(tmp1&&tmp2)
swap(tmp1->val, tmp2->val);
}
No comments:
Post a Comment