LeetCode 99: Recover Binary Search Tree

本文介绍了一种在不改变二叉搜索树结构的前提下,修复两个被错误交换节点的方法。提出了一种非递归中序遍历算法,并实现了一个常数空间复杂度的解决方案。

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

Difficulty: 4

Frequency: 2


Problem:

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?


Solution:

class Solution {
public:
    void recoverTree(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        TreeNode *p_last, *p_small, *p_big;
        bool b_big = true;
    	p_small = p_big = NULL;
        int i_last = INT_MIN;
        Traverse(root, i_last, p_last, p_small, p_big, b_big);
        i_last = p_small->val;
        p_small->val = p_big->val;
        p_big->val = i_last;
    }
    void Traverse(TreeNode * root, int & i_last, TreeNode * & p_last, TreeNode *& p_small, TreeNode *& p_big, bool & b_big)
    {
        if (root==NULL)
            return;
            
        if (root->left)
            Traverse(root->left, i_last, p_last, p_small, p_big, b_big);  

		if (i_last>root->val)
        {
            if (b_big)
            {
                p_big = p_last;
                b_big = !b_big;
                p_small = root;// Doing this is because the swapped two may be adjacent.
            }
            else
            {
                p_small = root;
                return;
            }
        }
        i_last = root->val;
        p_last = root;
        if (root->right)
            Traverse(root->right, i_last, p_last, p_small, p_big, b_big);
    }
};


Notes:

Lots of subtleties.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值