Easy C++ solution


  • 0
    A
    /**
     * 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) {
            if (root == NULL) {
                return separator;
            }
            
            string str = to_string(root->val) +  "," + serialize(root->left) + "," + serialize(root->right);
            return str;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            if (data.length() == 0 || data == separator) {
                return NULL;
            }
            
            queue<string> q;
            size_t pos = 0;
            size_t lastPos = 0;
            
            printf("tokens: ");
            while ((pos = data.find(",", lastPos)) != string::npos) {
                string node = data.substr(lastPos, pos - lastPos);
                lastPos = pos + 1;
                q.push(node);
            }
            return BuildTree(q);
        }
        
    protected:
        TreeNode *BuildTree(queue<string> &q) {
            if (q.empty()) {
                return NULL;
            }
            
            string str = q.front();
            q.pop();
            if (str == separator) {
                return NULL;
            }
            
            TreeNode *node = new TreeNode(atoi(str.c_str()));
            
            node->left = BuildTree(q);
            node->right = BuildTree(q);
            return node;
        }
        
        protected:
        
        const string separator = "X";
        
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.deserialize(codec.serialize(root));
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.