/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ std::vector split(const std::string& str, char delim) { std::vector tokens; size_t start = 0; size_t end = 0; while ((end = str.find(delim, start)) != std::string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; } class Codec { public: int ind; // Encodes a tree to a single string. string serialize(TreeNode* root) { if(!root) return "N"; return to_string(root->val)+","+serialize(root->left)+"," +serialize(root->right); } TreeNode* construct(vector data){ string res=data[ind]; if(data[ind]=="N") { ind+=1; return NULL; } int val=stoi(res); ind+=1;//index has to be incremented only after it is accessed TreeNode* curr=new TreeNode(val); curr->left=construct(data); curr->right=construct(data); return curr; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { ind=0; vector arr=split(data,','); return construct(arr); return NULL; } }; // Your Codec object will be instantiated and called as such: // Codec ser, deser; // TreeNode* ans = deser.deserialize(ser.serialize(root));