[LeetCode] 99. Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
一棵二叉搜索樹,有兩個節點換過來了,需要找出這兩個節點,換回來。
我們發現,一棵完好的BST,它的中序遍歷是一個有序的數組n。
從左往右找到第一個n[i-1] >n[i], n[i-1]爲第一個錯誤節點。
從右往左找到第一個n[i+1] < n[i], n[i+1]爲第二個錯誤節點,也就是從左往右找到最後一個n[i-1]>n[i], n[i]爲第二個錯誤節點。
void helper(TreeNode* root, vector<TreeNode*>& wrong_root, TreeNode* &last_root) {
if (root == NULL) return;
helper(root->left, wrong_root, last_root);
if (last_root && last_root->val > root->val) {
// 左邊第一個錯的肯定是錯誤節點
if (wrong_root[0] == NULL){
wrong_root[0] = last_root;
}
// 右邊最後一個錯的墾丁是錯誤節點
if (wrong_root[0] != NULL) {
wrong_root[1] = root;
}
}
last_root = root;
helper(root->right, wrong_root, last_root);
}
void recoverTree(TreeNode* root) {
vector<TreeNode*> wrong_root(2, 0);
TreeNode* last_root = NULL;
helper(root, wrong_root, last_root);
int tmp = wrong_root[0]->val;
wrong_root[0]->val = wrong_root[1]->val;
wrong_root[1]->val = tmp;
}