LeetCode详细分析 :: Recover Binary Search Tree [Tree]


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.

这里有几个知识点可以注意一下,是个不错的考察BST的题目。一、要如何找出这两个有乱序的位置呢?如果直接在树上考察,似乎关系有些模糊;那么,考虑一个性质,通过中序遍历,可以将BST按升序输出,eg:12 3 4 56 7,这里任意调换一下位置,构成16 3 4 5 2 7, 6 和 2将数列分割成了三份,每份独立时仍然保持升序(有可以能头尾的部门不包含元素),但是6 > 3, 5 > 2;说明,第一次出现 pre > cur的情况,pre是那个错误节点,第二次出现 pre > cur的情况,cur是错误节点,记录下来就可以了。

 二、有可能调换位置的元素在排序中相邻(树结构图中不一定相邻),一中提到的pre >cur的情况就发生重合,只有一次; 

代码如下:

class Solution {
private:
TreeNode *Pre, *node1, *node2;  //申明为成员变量,这样每个函数都可以访问,不必重复创建;

void inOrder(TreeNode *root){
    if (root == NULL)
        return;
    inOrder(root->left);
    if (Pre != NULL && Pre->val > root->val){  //第二次(也是最后一次)出现的才是正确位置,这里这样写避免了判断,直接覆盖
        node2 = root;
        if (node1 == NULL)             //利用 NULL 为是否为第一次出现的标记
            node1 = Pre;
    }
    Pre = root;
    inOrder(root->right);
}

public:
    void recoverTree(TreeNode *root) {
        Pre = NULL;
        node2 = node1 = NULL;
        
        inOrder(root);
        
        node1->val ^= node2->val;
        node2->val ^= node1->val;
        node1->val ^= node2->val;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值