LC 428. Serialize and Deserialize N-ary Tree
/* // 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) { string res=""; if(root==nullptr) return res; res+=to_string(root->val); res+=","; if(root->children.size()>0){ dfs(res, root); } //cout<<res<<"\n"; return res; } void dfs(string &res, Node* root){ res+="[,"; for(auto &child:root->children){ res+=to_string(child->val); res+=","; if(child->children.size()>0){ dfs(res,child); } } res+="],"; } // Decodes your encoded data to tree. Node* deserialize(string data) { if(data.size()==0) return nullptr; vector<string> parts=partString(data); //for(auto s:parts) cout<<s<<"\n"; Node* root=new Node(stoi(parts[0])); root->children=helper(parts,1,parts.size()-1); return root; } vector<Node*> helper(vector<string> &parts, int left, int right){ vector<Node*> res; int lo=left+1; while(lo<right){ Node* node=new Node(stoi(parts[lo])); if(lo+1<right && parts[lo+1]=="["){ int cnt=1; int hi=lo+2; while(hi<right){ if(parts[hi]=="[") cnt++; else if(parts[hi]=="]") cnt--; if(cnt==0) break; hi++; } node->children=helper(parts,lo+1,hi); lo=hi+1; }else{ lo++; } res.push_back(node); } return res; } vector<string> partString(string data){ int len=data.size(); int start=0; int end=0; vector<string> res; while(start<len){ while(data[end]!=',') end++; res.push_back(data.substr(start,end-start)); start=end+1; end=start; } return res; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));