层序遍历序列化与反序列化

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    char* Serialize(TreeNode *root) {
        if(root == NULL) return NULL;
        queue<TreeNode*> q;
        q.push(root);
        string res;
        while(!q.empty()){
            TreeNode* node = q.front(); q.pop();
            if(node != NULL){
                if(res != "") res += ",";
                res += to_string(node -> val);
                q.push(node -> left);
                q.push(node -> right);
            }else res += ",#";
        }
        char* resChars = new char[res.length()];
        for(int i = 0; i < res.length(); i ++){
            resChars[i] = res[i];
        }
        return resChars;
    }
    TreeNode* Deserialize(char *str) {
        if(str == NULL) return NULL;
        string s(str);
        vector<string> vec = splitToArr(s);
        TreeNode* root = new TreeNode(stoi(vec[0]));
        queue<TreeNode*> q;
        q.push(root);
        int i = 1;
        int n = vec.size();
        while(!q.empty()){
            TreeNode* node = q.front(); q.pop();
            if(vec[i] != "#"){
                node -> left = new TreeNode(stoi(vec[i]));
                q.push(node -> left);
            }
            i ++;
            if(vec[i] != "#"){
                node -> right = new TreeNode(stoi(vec[i]));
                q.push(node -> right);
            }
            i ++;
        }
        return root;
    }
    vector<string> splitToArr(string str){
        vector<string> res;
        string s;
        for(char ch:str){
            if(ch == ','){
                res.push_back(s);
                s = "";
            }else s += ch;
        }
        res.push_back(s);
        return res;
    }
};