Serialize and Deserialize Binary Tree
Serialize and Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
1 / \ 2 3 / \ 4 5as
"[1,2,3,null,null,4,5]"
, just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string res; if(!root){ res+="#."; return res; } res += to_string(root->val)+"."; res += serialize(root->left); res += serialize(root->right); return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { return _deserialize(data); } private: TreeNode* _deserialize(string& data) { int potpos = data.find_first_of('.',0); string num = data.substr(0,potpos); data.erase(0,potpos+1); if(num == "#") { return NULL; } TreeNode* root = new TreeNode(atoi(num.c_str())); root->left = _deserialize(data); root->right = _deserialize(data); return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
漂亮的代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { ostringstream oss; serialize(root,oss); return oss.str(); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { istringstream iss(data); return deserialize(iss); } private: void serialize(TreeNode* root,ostringstream& oss) { if(!root){ oss<<"# "; return; } oss<< root->val << ' '; serialize(root->left,oss); serialize(root->right,oss); } // Decodes your encoded data to tree. TreeNode* deserialize(istringstream& iss) { string val; iss>>val; if(val=="#") return NULL; TreeNode* root = new TreeNode(stoi(val)); root->left = deserialize(iss); root->right = deserialize(iss); return root; } };
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记