LeetCode "Recover Binary Search Tree"

An example of in-order traversal application. My intuition is that, we have to serialize it into an array and check, but in-order traversal does exactly the same thing. Then, you only need bookmark some runtime records to get it accepted :)

class Solution {
public:
    vector<TreeNode *> rec;
    queue<TreeNode *> q;
    void go(TreeNode *root)
    {
        if(root->left) go(root->left);
        //    update record
        if(q.size() == 2) q.pop();
        q.push(root);
        //    check
        if(q.size() > 1)
        {
            int v1 = q.back()->val;
            int v0 = q.front()->val;
            if(v0 > v1)
            {
                if(rec.empty())
                {
                    rec.push_back(q.front());
                    rec.push_back(q.back());
                }
                else
                {                    
                    rec[1] = q.back();
                }
            }
        }
        if(root->right) go(root->right);
    }
    void recoverTree(TreeNode *root) {
        if (!root)  return;
        if(!root->left && !root->right) return;
        go(root);
        int tmp = rec[0]->val;
        rec[0]->val = rec[1]->val;
        rec[1]->val = tmp;
    }
};
原文地址:https://www.cnblogs.com/tonix/p/3891384.html