Advertisement
spider68

297. Serialize and Deserialize Binary Tree

May 24th, 2021
690
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10. class Codec {
  11. public:
  12.  
  13.     // Encodes a tree to a single string.
  14.     string serialize(TreeNode* root) {
  15.         if(!root)return "#";
  16.         string s=to_string(root->val);
  17.         s+=","+serialize(root->left);
  18.         s+=","+serialize(root->right);
  19.         return s;
  20.     }
  21.  
  22.     TreeNode*deserial(stringstream &ss){
  23.         string node;
  24.         getline(ss,node,',');
  25.         if(node=="#")return NULL;
  26.         TreeNode*root=new TreeNode(stoi(node));
  27.         root->left=deserial(ss);
  28.         root->right=deserial(ss);
  29.        
  30.         return root;
  31.     }
  32.        
  33.     // Decodes your encoded data to tree.
  34.     TreeNode* deserialize(string data) {
  35.         stringstream ss(data);
  36.         return deserial(ss);
  37.     }
  38. };
  39.  
  40. // Your Codec object will be instantiated and called as such:
  41. // Codec ser, deser;
  42. // TreeNode* ans = deser.deserialize(ser.serialize(root));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement