LeetCode--Recover Binary Search Tree(C++)

题目描述:
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.
Subscribe to see which companies asked this question
这里写图片描述

题目解释:排序二叉树当中出现了两个元素的交换,这导致排序二叉树的性质不再,请恢复他原来的样子,且不能改变其结构。

思路分析:
(1)为空,没有逆序对,不做任何操作
(2) 不为空,判断容器大小:
  a.vec.size()==2,直接交换vec[0]和vec[1]两值即可。
  b.vec.size()==3,交换vec[0]和vec[2]第一个逆序的第一个数和第二个逆序的第二个数。
  c.vec.size()==4,交换vec[0]和vec[3]第一个逆序的第一个数和第二个逆序的第二个数。

代码实现如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void recoverTree(TreeNode *root) 
    {
        vector<TreeNode*> res;
        TreeNode* pre=NULL;
        recover(root,pre,res);
        if(res.size() > 0)
        {
            if(res.size() == 2)
                swap(res[0]->val,res[1]->val);
            if(res.size() == 3)
                swap(res[0]->val,res[2]->val);
            if(res.size() == 4)
                swap(res[0]->val,res[3]->val);
        }
    }
    void recover(TreeNode* root,TreeNode*& pre,vector<TreeNode*>& res)
    {
        if(root==NULL)
            return;

        recover(root->left,pre,res);
        if(pre!=NULL && pre->val > root->val)
        {
            res.push_back(pre);
            res.push_back(root);
        }
        pre=root;
        recover(root->right,pre,res);
    }
};

猜你喜欢

转载自blog.csdn.net/cherrydreamsover/article/details/81841715