加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

leetcode297 Serialize and Deserialize Binary Tree

发布时间:2020-12-14 04:42:05 所属栏目:大数据 来源:网络整理
导读:思路: 前序遍历 + 空节点标记。 实现: 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 Cod

思路:

前序遍历 + 空节点标记。

实现:

 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));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读