自己写的代码状况百出,根据失败的用例反复修改,看起来非常的乱,看了评论区大神的解法,学习体会思路,这里有一个非常值得学习的点是deserialize参数是string &,而我们需要不断的修改这个参数,所以增加一个辅助函数mydeserialize,这样在不更改给定接口的情况下,可以满足我们的需求。

/**
 * 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 == nullptr) return ".";
        return to_string(root->val) + ',' + serialize(root->left) + ','+serialize(root->right);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        return mydeserialize(data);
    }
private:
    TreeNode* mydeserialize(string & data) {
        if(data[0]=='.')
        {
            //skip #,
            if(data.size() > 1) 
                data = data.substr(2);
            
            return nullptr;
        }else{
            TreeNode * root = new TreeNode(helper(data));
            root->left = mydeserialize(data);
            root->right = mydeserialize(data);
            return root;
        }
    }
    int helper(string &data)
    {
        int loc = data.find(',');
        int val = stoi(data.substr(0,loc));
        data = data.substr(loc + 1);
        return val;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));