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);
}

本文介绍了一种方法来修复两个被错误交换节点的二叉搜索树(BST),通过中序遍历找到并交换这两个节点,从而在不改变树结构的情况下恢复BST的正确性。
3351

被折叠的 条评论
为什么被折叠?



