99. Recover Binary Search Tree

来源:互联网 发布:淘宝专业版店铺装修 编辑:程序博客网 时间:2024/06/05 10:23

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?

第一种方法:使用O(N)的存储空间,先中序遍历,然后找到交换的两个节点交换它们的值

class Solution {public:    void recoverTree(TreeNode* root)     {        vector<TreeNode *>temp;        inorder(root,temp);        TreeNode * mis1;        TreeNode * mis2;        for(int i=0;i+1<temp.size();i++)        {            if(temp[i]->val>temp[i+1]->val)            {                mis1=temp[i];                break;            }        }        for(int i=temp.size()-1;i-1>=0;i--)        {            if(temp[i]->val<temp[i-1]->val)            {                mis2=temp[i];                break;            }        }        int swap=mis1->val;        mis1->val=mis2->val;        mis2->val=swap;    }    void inorder(TreeNode* root,vector<TreeNode*>&temp)    {        if(!root)            return;        inorder(root->left,temp);        temp.push_back(root);        inorder(root->right,temp);    }};

第二种方法:不使用额外的空间,将当前节点和前一个节点进行比较就可以找到两个交换的节点

class Solution {public:    void recoverTree(TreeNode* root)     {        TreeNode *pre=NULL;//中序遍历当前节点的前一个节点        TreeNode *leftmistake=NULL;        TreeNode *rightmistake=NULL;        TreeNode *pnode=root;        int count=0;        stack<TreeNode *>q;        while(!q.empty()||pnode)        {            while(pnode)            {                q.push(pnode);                pnode=pnode->left;            }            TreeNode *cur=q.top();            if(pre==NULL)                pre=cur;            else            {                if(pre->val>cur->val)                {                    if(leftmistake==NULL)                        leftmistake=pre;                    rightmistake=cur;                    count++;                    if(count==2)                        break;                }                pre=cur;            }            pnode=cur->right;            q.pop();        }        int temp=leftmistake->val;        leftmistake->val=rightmistake->val;        rightmistake->val=temp;    }};

递归法

class Solution {public:    TreeNode *pre=new TreeNode(INT_MIN);//中序遍历当前节点的前一个节点    TreeNode *leftmistake=NULL;    TreeNode *rightmistake=NULL;    void recoverTree(TreeNode* root)     {        inorder(root);        swap(leftmistake->val,rightmistake->val);    }    void inorder(TreeNode *root)    {        if(!root)            return;        inorder(root->left);        if(leftmistake==NULL&&pre->val>root->val)            leftmistake=pre;        if(leftmistake&&pre->val>root->val)            rightmistake=root;        pre=root;        inorder(root->right);    }};
0 0
原创粉丝点击