Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Since the tree is BST, thus, in-order traverse would be in increasing order. Suppose the inorder traversal of BST is [1, 2, 3, 4, 5, 6]
Two nodes swaped, now, the wrong order is [1, 5, 3, 4, 2, 6].
We need to main two pointers to compare the previous value with current value. If previous value is higher than current value, that is where the disorder starts.
Here, 5 > 3, thus, the first node we are looking for is the "5". the two pointers will continue update until 4 > 2. 2 is the second pointer we are looking for.
Use two pointers (first and second) to memorize the two positions.
Need to pay attentions that prev, first, second are all reference since they need to be updated all the time.
void treeInorderTraverse(TreeNode* root, TreeNode*& prev, TreeNode*& first, TreeNode*& second) { if(!root) return; treeInorderTraverse(root->left, prev, first, second); if((prev != NULL) && (prev->val > root->val)) { if(first == NULL) first = prev; second = root; } prev = root; treeInorderTraverse(root->right, prev, first, second); } void recoverTree(TreeNode* root) { TreeNode* first = NULL; TreeNode* second = NULL; TreeNode* prev = NULL; treeInorderTraverse(root, prev, first, second); swap(first->val, second->val); }