C++ Level-Order Serialization
We can use a queue serialize the tree level-by-level. If a child node is null, we just add a separator (instead of null or something to save space).\n\nFor exam
We can use a queue serialize the tree level-by-level. If a child node is null, we just add a separator (instead of `null` or something to save space).\n\nFor example, this tree `[5,1,7,null,3,6,8,2,null,null]` will be serialized as `5,1,7,,3,6,8,2`.\n\n```cpp\nstring serialize(TreeNode* root) {\n    string res;\n    vector<TreeNode*> q{root};\n    while (!q.empty()) {\n        vector<TreeNode*> q1;\n        for (auto n : q) {\n            res += (n == nullptr ? "" : to_string(n->val)) + ",";\n            if (n != nullptr) {\n                q1.push_back(n->left);\n                q1.push_back(n->right);                    \n            }\n        }\n        swap(q, q1);\n    }\n    while (!res.empty() && res.back() == \',\')\n        res.pop_back();\n    return res;\n}\nTreeNode* readNode(string& data, int &i) {\n   string val;\n   while (i < data.size() && data[i] != \',\')\n        val += data[i++];\n    ++i;\n    return val.empty() ? nullptr : new TreeNode(stoi(val));\n}\nTreeNode* deserialize(string data) {\n    TreeNode tmp;\n    data = "," + data;\n    vector<TreeNode*> q{&tmp};\n    int i = 0;\n    while (!q.empty()) {\n        vector<TreeNode*> q1;\n        for (auto n : q) {\n            if (n != nullptr) {\n                q1.push_back(n->left = readNode(data, i));\n                q1.push_back(n->right = readNode(data, i));                \n            }\n        }\n        swap(q, q1);\n    }\n    return tmp.right;\n}\n```
[]