share my C++ solution


  • 0
    N
    /**
     * 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) return "|";
            return to_string(root->val) + "|" + serialize(root->left) + serialize(root->right);
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            int index = 0;
            return produce(data, index);
        }
    private:
        TreeNode* produce(string& data, int& u) {
            string tmp = "";
            while (data[u] != '|') {
                tmp += data[u];
                u ++;
            }
            u ++;
            if (tmp == "") return nullptr;
            TreeNode* root = new TreeNode(stoi(tmp));
            root->left = produce(data, u);
            root->right = produce(data, u);
            return root;
        }
    };
    
    // 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.