首页 > 其他 > 详细

297. 二叉树的序列化与反序列化

时间:2020-03-23 21:45:00      阅读:55      评论: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 {
12 public:
13     // Encodes a tree to a single string.
14     string serialize(TreeNode* root) 
15     {
16         if (root == NULL)
17             return "#_";
18         string res = to_string(root->val) + "_";
19         res += serialize(root->left);
20         res += serialize(root->right);
21         return res;
22     }
23 
24     // Decodes your encoded data to tree.
25     TreeNode* deserialize(string data) //"1_2_3_#_#_4_5_"切分成为[1,2,3,#,#,4,5]
26     {
27         stringstream ss(data);
28         string item;
29         queue<string> q;
30         while (getline(ss, item, _)) q.push(item);
31         return helper(q);
32     }
33     TreeNode* helper(queue<string>& q)
34     {
35         string val = q.front();
36         q.pop();
37         if (val == "#") return NULL;
38         TreeNode* head = new TreeNode(stoi(val));
39         head->left = helper(q);
40         head->right = helper(q);
41         return head;
42     }
43 };

 

297. 二叉树的序列化与反序列化

原文:https://www.cnblogs.com/yuhong1103/p/12555055.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!