/* // Definition for a Node. class Node { public: int val = NULL; vector<Node*> children; Node() {} Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ classCodec { public:
// Encodes a tree to a single string. stringserialize(Node* root){ string ret; if (root == NULL) return ret; helperSerialize(root, ret); return ret; } voidhelperSerialize(Node* root, string& ret){ ret += to_string(root->val); if (root->children.size() == 0) return; ret += '['; for(auto& item : root->children) { helperSerialize(item, ret); ret += ' '; } ret += ']'; return; } intextractNumber(string& s, int& index, int size){ int ret = 0; while(index < size && (s[index] <= '9' && s[index] >= '0')) { ret *= 10; ret += (s[index] - '0'); index += 1; } return ret; } // Decodes your encoded data to tree. Node* deserialize(string data){ Node* ret = NULL; int index = 0; int size = data.size(); helperDeserialize(data, ret, index, size); return ret; } voidhelperDeserialize(string& data, Node*& root, int& index, int size){ if (index >= size) return; int val = extractNumber(data, index, size); root = new Node(val, vector<Node*>()); if (index == size || data[index] != '[') return; index += 1; //Skip the '[' while (index < size && data[index]!= ']') { root->children.push_back(NULL); helperDeserialize(data, root->children.back(), index, size); index += 1; //Skip the whitespace } index += 1; //Skip the ']' } };
// Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));