[LeetCode] 99. Recover Binary Search Tree

[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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值