Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 69c2768

Browse files
committed
feat: add solutions to lc problem: No.0297
No.0297.Serialize and Deserialize Binary Tree
1 parent 9525eaa commit 69c2768

File tree

6 files changed

+562
-117
lines changed

6 files changed

+562
-117
lines changed

‎solution/0200-0299/0297.Serialize and Deserialize Binary Tree/README.md‎

Lines changed: 198 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@
5151
<li><code>-1000 <= Node.val <= 1000</code></li>
5252
</ul>
5353

54-
5554
## 解法
5655

5756
<!-- 这里可写通用的实现逻辑 -->
@@ -63,15 +62,184 @@
6362
<!-- 这里可写当前语言的特殊实现逻辑 -->
6463

6564
```python
66-
65+
# Definition for a binary tree node.
66+
# class TreeNode(object):
67+
# def __init__(self, x):
68+
# self.val = x
69+
# self.left = None
70+
# self.right = None
71+
72+
class Codec:
73+
74+
def serialize(self, root):
75+
"""Encodes a tree to a single string.
76+
77+
:type root: TreeNode
78+
:rtype: str
79+
"""
80+
81+
if root is None:
82+
return ''
83+
res = []
84+
85+
def preorder(root):
86+
if root is None:
87+
res.append("#,")
88+
return
89+
res.append(str(root.val) + ",")
90+
preorder(root.left)
91+
preorder(root.right)
92+
93+
preorder(root)
94+
return ''.join(res)
95+
96+
97+
def deserialize(self, data):
98+
"""Decodes your encoded data to tree.
99+
100+
:type data: str
101+
:rtype: TreeNode
102+
"""
103+
if not data:
104+
return None
105+
vals = data.split(',')
106+
107+
def inner():
108+
first = vals.pop(0)
109+
if first == '#':
110+
return None
111+
return TreeNode(int(first), inner(), inner())
112+
113+
return inner()
114+
115+
# Your Codec object will be instantiated and called as such:
116+
# ser = Codec()
117+
# deser = Codec()
118+
# ans = deser.deserialize(ser.serialize(root))
67119
```
68120

69121
### **Java**
70122

71123
<!-- 这里可写当前语言的特殊实现逻辑 -->
72124

73125
```java
126+
/**
127+
* Definition for a binary tree node.
128+
* public class TreeNode {
129+
* int val;
130+
* TreeNode left;
131+
* TreeNode right;
132+
* TreeNode(int x) { val = x; }
133+
* }
134+
*/
135+
public class Codec {
136+
private static final String NULL = "#";
137+
private static final String SEP = ",";
138+
139+
// Encodes a tree to a single string.
140+
public String serialize(TreeNode root) {
141+
if (root == null) {
142+
return "";
143+
}
144+
StringBuilder sb = new StringBuilder();
145+
preorder(root, sb);
146+
return sb.toString();
147+
}
148+
149+
private void preorder(TreeNode root, StringBuilder sb) {
150+
if (root == null) {
151+
sb.append(NULL + SEP);
152+
return;
153+
}
154+
sb.append(root.val + SEP);
155+
preorder(root.left, sb);
156+
preorder(root.right, sb);
157+
}
158+
159+
// Decodes your encoded data to tree.
160+
public TreeNode deserialize(String data) {
161+
if (data == null || "".equals(data)) {
162+
return null;
163+
}
164+
List<String> vals = new LinkedList<>();
165+
for (String x : data.split(SEP)) {
166+
vals.add(x);
167+
}
168+
return deserialize(vals);
169+
}
170+
171+
private TreeNode deserialize(List<String> vals) {
172+
String first = vals.remove(0);
173+
if (NULL.equals(first)) {
174+
return null;
175+
}
176+
TreeNode root = new TreeNode(Integer.parseInt(first));
177+
root.left = deserialize(vals);
178+
root.right = deserialize(vals);
179+
return root;
180+
}
181+
}
74182

183+
// Your Codec object will be instantiated and called as such:
184+
// Codec ser = new Codec();
185+
// Codec deser = new Codec();
186+
// TreeNode ans = deser.deserialize(ser.serialize(root));
187+
```
188+
189+
### **C++**
190+
191+
```cpp
192+
/**
193+
* Definition for a binary tree node.
194+
* struct TreeNode {
195+
* int val;
196+
* TreeNode *left;
197+
* TreeNode *right;
198+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
199+
* };
200+
*/
201+
class Codec {
202+
public:
203+
204+
// Encodes a tree to a single string.
205+
string serialize(TreeNode* root) {
206+
if (!root) return "";
207+
string s = "";
208+
preorder(root, s);
209+
return s;
210+
}
211+
212+
void preorder(TreeNode* root, string& s) {
213+
if (!root) s += "# ";
214+
else
215+
{
216+
s += to_string(root->val) + " ";
217+
preorder(root->left, s);
218+
preorder(root->right, s);
219+
}
220+
}
221+
222+
// Decodes your encoded data to tree.
223+
TreeNode* deserialize(string data) {
224+
if (data == "") return nullptr;
225+
stringstream ss(data);
226+
return deserialize(ss);
227+
}
228+
229+
TreeNode* deserialize(stringstream& ss) {
230+
string first;
231+
ss >> first;
232+
if (first == "#") return nullptr;
233+
TreeNode* root = new TreeNode(stoi(first));
234+
root->left = deserialize(ss);
235+
root->right = deserialize(ss);
236+
return root;
237+
}
238+
};
239+
240+
// Your Codec object will be instantiated and called as such:
241+
// Codec ser, deser;
242+
// TreeNode* ans = deser.deserialize(ser.serialize(root));
75243
```
76244
77245
### **JavaScript**
@@ -91,20 +259,8 @@
91259
* @param {TreeNode} root
92260
* @return {string}
93261
*/
94-
var serialize = function (root) {
95-
let data = [];
96-
let serializeRec = function (root) {
97-
if (!root) {
98-
data.push(1001);
99-
return null;
100-
}
101-
data.push(root.val);
102-
103-
serializeRec(root.left);
104-
serializeRec(root.right);
105-
}
106-
serializeRec(root);
107-
return data;
262+
var serialize = function(root) {
263+
return rserialize(root, '');
108264
};
109265
110266
/**
@@ -113,19 +269,35 @@ var serialize = function (root) {
113269
* @param {string} data
114270
* @return {TreeNode}
115271
*/
116-
var deserialize = function (data) {
117-
if (!data) {
118-
return null;
272+
var deserialize = function(data) {
273+
const dataArray = data.split(",");
274+
return rdeserialize(dataArray);
275+
};
276+
277+
const rserialize = (root, str) => {
278+
if (root === null) {
279+
str += "#,";
280+
} else {
281+
str += root.val + '' + ",";
282+
str = rserialize(root.left, str);
283+
str = rserialize(root.right, str);
119284
}
120-
let curVal = data.shift();
121-
if (curVal == 1001) {
285+
return str;
286+
}
287+
288+
const rdeserialize = (dataList) => {
289+
if (dataList[0] === "#") {
290+
dataList.shift();
122291
return null;
123292
}
124-
let node = new TreeNode(curVal);
125-
node.left = deserialize(data);
126-
node.right = deserialize(data);
127-
return node;
128-
};
293+
294+
const root = new TreeNode(parseInt(dataList[0]));
295+
dataList.shift();
296+
root.left = rdeserialize(dataList);
297+
root.right = rdeserialize(dataList);
298+
299+
return root;
300+
}
129301
130302
/**
131303
* Your functions will be called as such:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /