码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Recover Binary Search Tree"

时间:2014-08-05 03:03:48      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   div   amp   size   

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

LeetCode "Recover Binary Search Tree",布布扣,bubuko.com

LeetCode "Recover Binary Search Tree"

标签:style   blog   color   io   ar   div   amp   size   

原文地址:http://www.cnblogs.com/tonix/p/3891384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!