Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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<std::string> split(const std::string& str, char delim) {
- std::vector<std::string> 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<string> 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<string> 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));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement