首页 > 其他 > 详细

LeetCode "Recover Binary Search Tree"

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

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"

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!