[LeetCode] 99. Recover Binary Search Tree

来源:互联网 发布:无锡算法工程师招聘 编辑:程序博客网 时间:2024/05/31 18:39

[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;    }
0 0