# [LeetCode] 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   5


as "[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.

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

 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 private:
12     void _serialize(TreeNode *root, ostringstream &sout) {
13         if (root == NULL) {
14             sout << "# ";
15             return;
16         }
17         sout << root->val << " ";
18         _serialize(root->left, sout);
19         _serialize(root->right, sout);
20     }
21     void _deserialize(TreeNode *&root, istringstream &sin) {
22         int val;
23         string tmp;
24         if (sin >> tmp && tmp != "#") {
25             val = stoi(tmp);
26         } else {
27             return;
28         }
29         root = new TreeNode(val);
30         _deserialize(root->left, sin);
31         _deserialize(root->right, sin);
32     }
33 public:
34
35     // Encodes a tree to a single string.
36     string serialize(TreeNode* root) {
37         ostringstream sout;
38         _serialize(root, sout);
39         return sout.str();
40     }
41
42     // Decodes your encoded data to tree.
43     TreeNode* deserialize(string data) {
44         istringstream sin(data);
45         TreeNode *root = NULL;
46         _deserialize(root, sin);
47         return root;
48     }
49 };
50
51 // Your Codec object will be instantiated and called as such:
52 // Codec codec;
53 // codec.deserialize(codec.serialize(root));

posted @ 2015-10-29 17:54  Eason Liu  阅读(550)  评论(0编辑  收藏  举报