Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- // Definition for a Node.
- class Node {
- public:
- int val;
- vector<Node*> children;
- Node() {}
- Node(int _val) {
- val = _val;
- }
- Node(int _val, vector<Node*> _children) {
- val = _val;
- children = _children;
- }
- };
- */
- class Codec {
- public:
- // Encodes a tree to a single string.
- string serialize(Node* root) {
- // If tree is null.
- if(!root) return "#";
- // Add current node's value and then it's length.
- string repr = "";
- repr += to_string(root->val)+',';
- repr += to_string((root->children).size())+',';
- // Add each child's representation.
- for(int i=0; i<(root->children).size(); i++)
- repr += serialize((root->children)[i]);
- return repr;
- }
- // Decodes your encoded data to tree.
- Node* deserialize(string data) {
- return dserialize(data);
- }
- Node* dserialize(string &data){
- // If tree is null.
- if(data[0] == '#') return NULL;
- // Create node with value.
- int pos = data.find(',');
- int val = stoi(data.substr(0, pos));
- data = data.substr(pos+1);
- Node *node = new Node(val);
- // Find number of children and recurse over each.
- pos = data.find(',');
- int numChild = stoi(data.substr(0, pos));
- data = data.substr(pos+1);
- for(int i=0; i<numChild; i++)
- (node->children).push_back(dserialize(data));
- return node;
- }
- };
- // Your Codec object will be instantiated and called as such:
- // Codec codec;
- // codec.deserialize(codec.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment