zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    OSX中zsh新增环境变量
    新的开始 春光明媚
    tmux
    继承
    6
    Object类
    网页收藏
    画王八
    ES6 语法之import export
    ES6 语法 之 destructuring
  • 原文地址:https://www.cnblogs.com/tonix/p/3891384.html
Copyright © 2011-2022 走看看