LeetCode 99. Recover Binary Search Tree (BST, preorder)

topic

Meaning of the questions: to give you a BST, in which any two elements are exchanged, and let you exchange the elements of recovery.

Solution: in order traversal of BST is an orderly array, two elements are exchanged, we can find a loop for these two figures. Traversing from small to large, to maintain a value of max, it represents the maximum value of the current through the elements. Since the two elements are exchanged, so there must be a period of max is constant, until it encounters a larger than max elements, so you should max and before the largest of an element switching over. Of course, if the end has not yet traversed bigger than max, then max is the greatest, so swap the last element on it.

The above process can be done in order traversal.

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);
     }

    }
    };
    ```

Guess you like

Origin www.cnblogs.com/dacc123/p/12201573.html