LeetCode 99. Recover Binary Search Tree(BST,中序遍历)

题目

题意:给你一个BST,其中任意两个元素被交换过了,让你把交换的元素复原。

题解:BST的中序遍历是个有序的数组,那么两个元素被交换了,我们可以for循环一次找出这两个数字。从小到大遍历,维护一个值max,表示当前遍历元素的最大值。由于两个元素被交换了,所以max一定有一段时间是不变的,直到遇到一个比max大的元素,那么max就应该和这个最大的元素之前一个元素交换过来。当然如果遍历结束了还没有比max大的,那么max就是最大的,所以交换最后一个元素就可以了。

以上操作可以在中序遍历的过程中完成。

c++
```
/**

  • Definition for a binary tree node.
  • struct TreeNode {
  • int val;
  • TreeNode *left;
  • TreeNode *right;
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  • };
    */
    class Solution {
    public:

    TreeNode* last;
    TreeNode* pre;

    int tag=0;
    int ans=0;

    int m = -123987523;
    void recoverTree(TreeNode* root) {

     if(root==NULL)
         return;
    
     last = new TreeNode(m);
    
     fun(root);
    
     if(ans==0)
     {
         int temp = pre->val;
         pre->val = last->val;
         last->val = temp;
     }

    }

    void fun(TreeNode* root)
    {
    if(root->left!=NULL)
    {
    fun(root->left);
    }

     if(last->val == m )
     {
         last=root;
     }
     else if(last->val<root->val)
     {
         if(tag==1)
         {
             int temp = pre->val;
             pre->val = last->val;
             last->val = temp;
             ans=1;
         }
         last=root;
         tag=0;
     }
     else
     {
         tag=1;
     }
    
     pre=root;
    
     if(root->right!=NULL)
     {
         fun(root->right);
     }

    }
    };
    ```

猜你喜欢

转载自www.cnblogs.com/dacc123/p/12201573.html