leetcode:Recover Binary Search Tree

又有好几天没有做题,这道题看了题目很久了,一直在思考,因为要求常数空间而实际上递归解法需要的空间并不是常数级别的。看到网上的解答,有人说可以用Morris方法遍历二叉树,这样可以在o(1)空间复杂度和o(n)时间复杂度完成二叉树的遍历。但是好几天没有刷题了,想要快点做出这道题,所以还是用了递归的解法。Morris方法下次再做吧~

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.

Show Tags
Have you met this question in a real interview? 
Yes
 
No

题目地址:https://oj.leetcode.com/problems/recover-binary-search-tree/

解题思路:思路是先得到二叉树的中序遍历,找出顺序不对的数,如果只有一个地方顺序不对交换两个数;如果出现两个顺序不对的地方,把第一个地方的较大的数和第二个地方较小的数交换。用change这个vector来存储顺序不对的节点。不管最后change中是只有两个节点还是有4个节点,都是交换第一个节点和最后一个节点的值。

代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *pre;
    vector<TreeNode *> change;
    void recoverTree(TreeNode *root) {
        //思路是先得到二叉树的中序遍历,找出顺序不对的数,如果只有一个地方顺序不对交换两个数;如果出现两个顺序不对的地方,把第一个地方的较大的数和第二个地方较小的数交换
        if(root==NULL) return;
        if(root->left==NULL&&root->right==NULL) return;
        
        pre=NULL;
        change.clear();
        inorder(root);
        
        //交换change第一个节点和最后一个节点的值
        if(change.size()>0){
            int tmp=change[0]->val;
            change[0]->val=change[change.size()-1]->val;
            change[change.size()-1]->val=tmp;
        }
    }
    
    void inorder(TreeNode *root){
        if(root == NULL) return;
        
        inorder(root->left);
        if(pre == NULL){
            pre = root;
        }else{
            if(pre->val>root->val){
                change.push_back(pre);
                change.push_back(root);
            }
            pre = root;
        }
        inorder(root->right);
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值