LeetCode——Recover Binary Search Tree

本文介绍了一种不改变二叉搜索树结构的情况下,恢复被错误交换的两个元素的方法。通过中序遍历找到需要交换的节点,并进行值的交换。文章提供了一个常数空间复杂度的解决方案。

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

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:
A solution using O( n ) space is pretty straight forward. Could you devise a constant space solution?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

» Solve this problem


提示1:

先看一个递增序列:1 2 3 4 5 6 7.

交换4和6:1 2 3 6 5 4 7

注意,6是第一个大于后一个元素的(6 > 5, 5 > 4),4是最后一个小于前一个元素的(5 < 6,4 < 5)。


提示2:

不用O(n)空间来记录整个序列,根据提示1,只记录前一个节点即可。


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    TreeNode *node1, *node2;
    TreeNode *pre;
    
    void traverse(TreeNode *root) {
        if (root == NULL) {
            return;
        }    
        traverse(root->left);
        if (pre != NULL && pre->val > root->val) {
            node2 = root;
            if (node1 == NULL) {
                node1 = pre;
            }
        }
        pre = root;
        traverse(root->right);
    }
    
public:
    void recoverTree(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        node1 = node2 = NULL;
        pre = NULL;
        traverse(root);        
        node1->val ^= node2->val;
        node2->val ^= node1->val;
        node1->val ^= node2->val;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值