【树】二叉树的序列化与反序列化

时间:2020-05-16 15:00:18   收藏:0   阅读:46

题目:

技术分享图片

 

 

解答:

先序遍历进行处理。

 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     // 先序遍历
15     string serialize(TreeNode* root) 
16     {
17         if (NULL == root)
18         {
19             return "null,";
20         }
21         
22         return std::to_string(root->val) + "," + serialize(root->left) + serialize(root->right);    
23     }
24 
25     // Decodes your encoded data to tree.
26     TreeNode* deserialize(string data) 
27     {
28         queue<std::string> q;
29         string s;
30         
31         for (int i = 0; i < data.size(); i++)
32         {
33             if (data[i] == ,)
34             {
35                 q.push(s);
36                 s = "";
37                 continue;
38             }
39             
40             s += data[i];
41         }
42        
43         if (s.size() != 0)
44         {
45             q.push(s);
46         }
47         
48         return deserializehepler(q);
49     }
50     
51     TreeNode* deserializehepler(queue<std::string> &q)
52     {
53         string s = q.front();
54         q.pop();
55         if (s == "null")
56         {
57             return NULL;
58         }
59         
60         TreeNode *root = new TreeNode(stoi(s));
61         root->left = deserializehepler(q);
62         root->right = deserializehepler(q);
63         
64         return root;  
65     }
66 };
67 
68 // Your Codec object will be instantiated and called as such:
69 // Codec codec;
70 // codec.deserialize(codec.serialize(root));

 

原文:https://www.cnblogs.com/ocpc/p/12899923.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!