LeetCode 99. Recover Binary Search Tree

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值