Posted on

Description

Submission

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        // level order traversal
        queue<TreeNode*> q;
        q.push(root);
        string ret;
        while(!q.empty()) {
            int n = q.size();

            for(int i = 0; i < n; ++i) {
                TreeNode* cur = q.front();
                q.pop();    

                if(cur) {
                    ret += to_string(cur->val);
                }
                ret += ',';
                
                if(cur) {
                    q.push(cur->left);
                    q.push(cur->right);
                }
            }
        }

        return ret;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        queue<TreeNode*> treeNodes;
        for(auto it = data.begin(); it != data.end(); ++it) {
            auto it2 = find(it, data.end(), ',');
            if(it == it2) treeNodes.push(nullptr);
            else {
                int val = stoi(data.substr(it-data.begin(), it2-it));
                treeNodes.push(new TreeNode(val));
                it = it2;
            }
        }

        TreeNode* ret = treeNodes.front();
        treeNodes.pop();
        queue<TreeNode*> toConnect;
        toConnect.push(ret);

        while(!treeNodes.empty()) {
            TreeNode* cur = toConnect.front();
            toConnect.pop();

            if(cur) cur->left = treeNodes.front();
            treeNodes.pop();
            if(cur) cur->right = treeNodes.front();
            treeNodes.pop();

            if(cur->left) toConnect.push(cur->left);
            if(cur->right) toConnect.push(cur->right);
        }
       
       return ret;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

Leave a Reply

Your email address will not be published. Required fields are marked *