-
Notifications
You must be signed in to change notification settings - Fork 43
/
serialize-and-deserialize-bst.py
563 lines (480 loc) · 16 KB
/
serialize-and-deserialize-bst.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
"""
449. Serialize and Deserialize BST
Medium
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Example 1:
Input: root = [2,1,3]
Output: [2,1,3]
Example 2:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 104].
0 <= Node.val <= 104
The input tree is guaranteed to be a binary search tree.
"""
# V0
# IDEA : BFS + queue op
class Codec:
def serialize(self, root):
if not root:
return '{}'
res = [root.val]
q = [root]
while q:
new_q = []
for i in range(len(q)):
tmp = q.pop(0)
if tmp.left:
q.append(tmp.left)
res.extend( [tmp.left.val] )
else:
res.append('#')
if tmp.right:
q.append(tmp.right)
res.extend( [tmp.right.val] )
else:
res.append('#')
while res and res[-1] == '#':
res.pop()
return '{' + ','.join(map(str, res)) + '}'
def deserialize(self, data):
if data == '{}':
return
nodes = [ TreeNode(x) for x in data[1:-1].split(",") ]
root = nodes.pop(0)
p = [root]
while p:
new_p = []
for n in p:
if nodes:
left_node = nodes.pop(0)
if left_node.val != '#':
n.left = left_node
new_p.append(n.left)
else:
n.left = None
if nodes:
right_node = nodes.pop(0)
if right_node.val != '#':
n.right = right_node
new_p.append(n.right)
else:
n.right = None
p = new_p
return root
# V0' : BFS + collection.dequeue op
class Codec:
def serialize(self, root):
if not root:
return '{}'
p = [root]
result = [root.val]
while p:
new_p = []
for n in p:
if n.left:
new_p.append(n.left)
result.extend([n.left.val])
else:
result.extend('#')
if n.right:
new_p.append(n.right)
result.extend([n.right.val])
else:
result.extend('#')
p = new_p
while result and result[-1] == '#':
result.pop()
return '{' + ','.join(map(str, result)) + '}'
def deserialize(self, data):
if data == '{}':
return
nodes = collections.deque([TreeNode(n) for n in data[1:-1].split(',')])
root = nodes.popleft()
p = [root]
while p:
new_p = []
for n in p:
if nodes:
left_node = nodes.popleft()
if left_node.val != '#':
n.left = left_node
new_p.append(n.left)
else:
n.left = None
if nodes:
right_node = nodes.popleft()
if right_node.val != '#':
n.right = right_node
new_p.append(n.right)
else:
n.right = None
p = new_p
return root
# V0''
class Codec:
def serialize(self, root):
vals = []
self._preorder(root, vals)
return ','.join(vals)
def _preorder(self, node, vals):
if node:
vals.append(str(node.val))
self._preorder(node.left, vals)
self._preorder(node.right, vals)
def deserialize(self, data):
vals = collections.deque(map(int, data.split(','))) if data else []
return self._build(vals, -float('inf'), float('inf'))
def _build(self, vals, minVal, maxVal):
if vals and minVal < vals[0] < maxVal:
val = vals.popleft()
root = TreeNode(val)
root.left = self._build(vals, minVal, val)
root.right = self._build(vals, val, maxVal)
return root
else:
return None
# V1
# IDEA : same as LC 297
# https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/93283/Python-solution-using-BST-property
class Codec:
def serialize(self, root):
vals = []
self._preorder(root, vals)
return ','.join(vals)
def _preorder(self, node, vals):
if node:
vals.append(str(node.val))
self._preorder(node.left, vals)
self._preorder(node.right, vals)
def deserialize(self, data):
vals = collections.deque(map(int, data.split(','))) if data else []
return self._build(vals, -float('inf'), float('inf'))
def _build(self, vals, minVal, maxVal):
if vals and minVal < vals[0] < maxVal:
val = vals.popleft()
root = TreeNode(val)
root.left = self._build(vals, minVal, val)
root.right = self._build(vals, val, maxVal)
return root
else:
return None
# V1'
# IDEA : BST property
# https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/212043/Python-solution
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def dfs(root):
if not root:
return
res.append(str(root.val) + ",")
dfs(root.left)
dfs(root.right)
res = []
dfs(root)
return "".join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
lst = data.split(",")
lst.pop()
stack = []
head = None
for n in lst:
n = int(n)
if not head:
head = TreeNode(n)
stack.append(head)
else:
node = TreeNode(n)
if n < stack[-1].val:
stack[-1].left = node
else:
while stack and stack[-1].val < n:
u = stack.pop()
u.right = node
stack.append(node)
return head
# V1''
# IDEA : BST property
# https://leetcode.com/problems/serialize-and-deserialize-bst/discuss/212043/Python-solution
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def dfs(root):
if not root:
return
res.append(str(root.val) + ",")
dfs(root.left)
dfs(root.right)
res = []
dfs(root)
return "".join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def helper(arr, i, j):
if i > j:
return
if i == j:
node = TreeNode(arr[i])
return node
for k in range(i+1, j+1):
if arr[k] > arr[i]:
l = helper(arr, i+1, k-1)
r = helper(arr, k, j)
root = TreeNode(arr[i])
root.left = l
root.right = r
return root
l = helper(arr, i+1, j)
root = TreeNode(arr[i])
root.left = l
return root
arr = data.split(",")
arr.pop()
data = [int(x) for x in arr]
return helper(data, 0, len(data)-1)
# V1''
# http://bookshadow.com/weblog/2015/10/26/leetcode-serialize-and-deserialize-binary-tree/
class Codec:
def serialize(self, root):
def doit(node):
if node:
vals.append(str(node.val))
doit(node.left)
doit(node.right)
else:
vals.append('#')
vals = []
doit(root)
return ' '.join(vals)
def deserialize(self, data):
def doit():
val = next(vals)
if val == '#':
return None
node = TreeNode(int(val))
node.left = doit()
node.right = doit()
return node
vals = iter(data.split())
return doit()
# V1'''
# http://bookshadow.com/weblog/2015/10/26/leetcode-serialize-and-deserialize-binary-tree/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return '[]'
res = [root.val]
q = collections.deque([root])
while q:
front = q.popleft()
if front.left:
q.append(front.left)
if front.right:
q.append(front.right)
res.append(front.left.val if front.left else 'null')
res.append(front.right.val if front.right else 'null')
while res and res[-1] == 'null':
res.pop()
return '[' + ','.join(map(str, res)) + ']'
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if data == '[]':
return None
nodes = collections.deque([[TreeNode(o), None][o == 'null']
for o in data[1:-1].split(',')])
q = collections.deque([nodes.popleft()]) if nodes else None
root = q[0] if q else None
while q:
parent = q.popleft()
left = nodes.popleft() if nodes else None
right = nodes.popleft() if nodes else None
parent.left, parent.right = left, right
if left:
q.append(left)
if right:
q.append(right)
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
# V1'''''
# http://bookshadow.com/weblog/2015/10/26/leetcode-serialize-and-deserialize-binary-tree/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import json
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return 'null'
nodes = collections.deque([root])
maps = collections.deque([{'v' : root.val}])
tree = maps[0]
while nodes:
frontNode = nodes.popleft()
frontMap = maps.popleft()
if frontNode.left:
frontMap['l'] = {'v' : frontNode.left.val}
nodes.append(frontNode.left)
maps.append(frontMap['l'])
if frontNode.right:
frontMap['r'] = {'v' : frontNode.right.val}
nodes.append(frontNode.right)
maps.append(frontMap['r'])
return json.dumps(tree)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
tree = json.loads(data)
if not tree:
return None
root = TreeNode(tree['v'])
maps = collections.deque([tree])
nodes = collections.deque([root])
while nodes:
frontNode = nodes.popleft()
frontMap = maps.popleft()
left, right = frontMap.get('l'), frontMap.get('r')
if left:
frontNode.left = TreeNode(left['v'])
maps.append(left)
nodes.append(frontNode.left)
if right:
frontNode.right = TreeNode(right['v'])
maps.append(right)
nodes.append(frontNode.right)
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
# V1''''''
# https://www.jiuzhang.com/solution/serialize-and-deserialize-bst/#tag-highlight-lang-python
class Codec:
def serialize(self, root):
# write your code here
if not root:
return '{}'
p = [root]
result = [root.val]
while p:
new_p = []
for n in p:
if n.left:
new_p.append(n.left)
result.extend([n.left.val])
else:
result.extend('#')
if n.right:
new_p.append(n.right)
result.extend([n.right.val])
else:
result.extend('#')
p = new_p
while result and result[-1] == '#':
result.pop()
return '{' + ','.join(map(str, result)) + '}'
def deserialize(self, data):
if data == '{}':
return
nodes = collections.deque([TreeNode(n) for n in data[1:-1].split(',')])
root = nodes.popleft()
p = [root]
while p:
new_p = []
for n in p:
if nodes:
left_node = nodes.popleft()
if left_node.val != '#':
n.left = left_node
new_p.append(n.left)
else:
n.left = None
if nodes:
right_node = nodes.popleft()
if right_node.val != '#':
n.right = right_node
new_p.append(n.right)
else:
n.right = None
p = new_p
return root
# V2
# Time: O(n)
# Space: O(h)
import collections
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec(object):
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def serializeHelper(node, vals):
if node:
vals.append(node.val)
serializeHelper(node.left, vals)
serializeHelper(node.right, vals)
vals = []
serializeHelper(root, vals)
return ' '.join(map(str, vals))
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def deserializeHelper(minVal, maxVal, vals):
if not vals:
return None
if minVal < vals[0] < maxVal:
val = vals.popleft()
node = TreeNode(val)
node.left = deserializeHelper(minVal, val, vals)
node.right = deserializeHelper(val, maxVal, vals)
return node
else:
return None
vals = collections.deque([int(val) for val in data.split()])
return deserializeHelper(float('-inf'), float('inf'), vals)