Loading

剑指 Offer 37. 序列化二叉树

 

 

思路

这里使用层序遍历产生的序列当成序列化,再使用此序列层序创建二叉树即对应反序列化。

使用“#”代表空节点,并且各节点的值在序列化的字符串中以空格分隔。

注:本题解法不唯一,如使用:先序遍历进行序列化 + 先序创建反序列化 也是可以的。

 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         if(root == NULL)
17             return "";
18 
19         string res = "";
20         queue<TreeNode*> Q;
21         Q.push(root);
22         while(!Q.empty()) {
23             TreeNode *t = Q.front();
24             Q.pop();
25             
26             if(t != NULL) {
27                 res += to_string(t->val) + " ";
28                 Q.push(t->left);
29                 Q.push(t->right);
30             } else {
31                 res += "# ";
32             }
33         }
34         return res;
35     }
36 
37     // Decodes your encoded data to tree.
38     //层序创建二叉树
39     TreeNode* deserialize(string data) {
40         if(data == "")
41             return NULL;
42         
43         istringstream is(data);
44         string value;
45         is >> value;
46         TreeNode *node = new TreeNode(stoi(value));
47         queue<TreeNode*> Q;
48         Q.push(node);
49         while(!Q.empty()) {
50             TreeNode *t = Q.front();
51             Q.pop();
52             
53             string lvalue, rvalue;
54             is >> lvalue;
55             is >> rvalue;
56 
57             if(lvalue == "#") {
58                 t->left = NULL;
59             } else {
60                 t->left = new TreeNode(stoi(lvalue));
61                 Q.push(t->left);
62             }
63 
64             if(rvalue == "#") {
65                 t->right = NULL;
66             } else {
67                 t->right = new TreeNode(stoi(rvalue));
68                 Q.push(t->right);
69             }
70         }
71 
72         return node;
73     }
74 };
75 
76 // Your Codec object will be instantiated and called as such:
77 // Codec codec;
78 // codec.deserialize(codec.serialize(root));

 

posted @ 2020-11-02 17:53  拾月凄辰  阅读(49)  评论(0编辑  收藏  举报