首页 > 其他 > 详细

leetcode297 Serialize and Deserialize Binary Tree

时间:2019-07-08 09:06:38      阅读:96      评论: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 
14     // Encodes a tree to a single string.
15     string serialize(TreeNode* root)
16     {
17         if (!root) return "x";
18         return to_string(root->val) + , + serialize(root->left) + , + serialize(root->right);
19     }
20 
21     // Decodes your encoded data to tree.
22     TreeNode* deserialize(string data)
23     {
24         data += ,;
25         int l = data.length();
26         queue<string> q; int last = 0;
27         for (int i = 0; i < l; i++)
28         {
29             if (data[i] == ,)
30             {
31                 q.push(data.substr(last, i - last));
32                 last = i + 1;
33             }
34         }
35         return work(q);
36     }
37     
38     TreeNode* work(queue<string>& q)
39     {
40         string t = q.front(); q.pop();
41         if (t == "x") return NULL;
42         TreeNode* res = new TreeNode(stoi(t));
43         res->left = work(q);
44         res->right = work(q);
45         return res;
46     }
47 
48 };
49 
50 // Your Codec object will be instantiated and called as such:
51 // Codec codec;
52 // codec.deserialize(codec.serialize(root));

leetcode297 Serialize and Deserialize Binary Tree

原文:https://www.cnblogs.com/wangyiming/p/11148989.html

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