1. 程式人生 > >[Algorithm] 7. Serialize and Deserialize Binary Tree

[Algorithm] 7. Serialize and Deserialize Binary Tree

markdown ras ive rip saving test ron fir esc

Description

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called ‘serialization‘ and reading back from the file to reconstruct the exact same binary tree is ‘deserialization‘.

Example

An example of testdata: Binary tree {3,9,20,#,#,15,7}

, denote the following structure:

  3
 / 9  20
  /   15   7

Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

Solution

 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * TreeNode(int val) { 8 * this->val = val; 9 * this->left = this->right = NULL; 10 * } 11 * } 12 */ 13 14 class Solution { 15 private: 16 void serializeBTree(TreeNode* node, string& output){
17 if(node != NULL){ 18 output = output+to_string(node->val)+ ; 19 serializeBTree(node->left, output); 20 serializeBTree(node->right, output); 21 }else{ 22 output+="# "; 23 } 24 } 25 26 TreeNode* deserializeBTree(string& data){ 27 if(data.length() == 0) return NULL; 28 29 // Get the first string which is divided with space character. 30 int pos = data.find( ); 31 char *str = new char[pos]; 32 data.copy(str, pos, 0); 33 data.erase(0,pos+1); 34 if(str[0] == #) return NULL; 35 36 TreeNode *root = new TreeNode(atoi(str)); 37 if(str) delete str; 38 39 root->left = deserializeBTree(data); 40 root->right = deserializeBTree(data); 41 42 return root; 43 } 44 public: 45 /** 46 * This method will be invoked first, you should design your own algorithm 47 * to serialize a binary tree which denote by a root node to a string which 48 * can be easily deserialized by your own "deserialize" method later. 49 */ 50 string serialize(TreeNode * root) { 51 // Serialize the tree in priority arrangement. 52 string output; 53 serializeBTree(root, output); 54 return output; 55 } 56 57 /** 58 * This method will be invoked second, the argument data is what exactly 59 * you serialized at method "serialize", that means the data is not given by 60 * system, it‘s given by your own serialize method. So the format of data is 61 * designed by yourself, and deserialize it here as you serialize it in 62 * "serialize" method. 63 */ 64 TreeNode * deserialize(string &data) { 65 // Deserialize the tree in priority arrangement. 66 TreeNode *root = NULL; 67 root = deserializeBTree(data); 68 return root; 69 } 70 };

Tips

This solution makes use of the priority arrangement of the binary tree. Strings which are used for saving result are divided with a space character.

Alternative Solution

 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 
14 class Solution {
15 public:
16     /**
17      * This method will be invoked first, you should design your own algorithm 
18      * to serialize a binary tree which denote by a root node to a string which
19      * can be easily deserialized by your own "deserialize" method later.
20      */
21     string serialize(TreeNode * root) {
22         // Serialize the tree in BFS(Breadth First Search).
23         std::ostringstream output;
24         std::queue<TreeNode*> que;
25         if(root)    que.push(root);
26         
27         while(!que.empty()){    // If queue is not empty, process. 
28             TreeNode *node = que.front();
29             if(node){
30                 output << node->val <<  ;
31                 que.push(node->left);
32                 que.push(node->right);
33             }else{
34                 output << "# ";
35             }
36             que.pop();
37         }
38         
39         return output.str();
40     }
41 
42     /**
43      * This method will be invoked second, the argument data is what exactly
44      * you serialized at method "serialize", that means the data is not given by
45      * system, it‘s given by your own serialize method. So the format of data is
46      * designed by yourself, and deserialize it here as you serialize it in 
47      * "serialize" method.
48      */
49     TreeNode * deserialize(string &data) {
50         // Deserialize the tree in priority arrangement.
51         if(data.empty())    return NULL;
52         std::queue<TreeNode*> que;
53         std::istringstream  input(data);
54         string  str;
55         input >> str;
56         TreeNode *root = new TreeNode(stoi(str));
57         que.push(root);
58         
59         while(!que.empty()){
60             TreeNode* node = que.front(); que.pop();
61             if(!(input>>str))  break;
62             if(str != "#"){
63                 node->left = new TreeNode(stoi(str));
64                 que.push(node->left);
65             }
66             
67             if(!(input>>str))  break;
68             if(str != "#"){
69                 node->right = new TreeNode(stoi(str));
70                 que.push(node->right);
71             }
72         }
73 
74         return root;
75     }
76 };

Tips

This alternative solution we can use is through BFS method. We make use of the stream string library to process the storage of the binary tree.

[Algorithm] 7. Serialize and Deserialize Binary Tree