-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS-serialize-and-deserialize-binary-tree.py
66 lines (59 loc) · 1.7 KB
/
BFS-serialize-and-deserialize-binary-tree.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
# 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
"""
print(root)
if root == None:
return ''
q = [root]
string = ''
while len(q) > 0:
current = q.pop(0)
if current is not None:
string = string+str(current.val)+','
else:
string = string+str(current)+','
if current == None:
continue
# print(string)
q.append(current.left)
q.append(current.right)
return string
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if data == '':
return []
data_list = data.split(',')
data_list.pop(-1)
root = TreeNode(int(data_list[0]))
q = [root]
i = 0
while len(q) > 0:
parent = q.pop(0)
# 开始build cur 的左右子树
i = i+1
left = data_list[i]
if left != 'None':
parent.left = TreeNode(int(left))
q.append(parent.left)
else:
parent.left = None
i = i+1
right = data_list[i]
if right != 'None':
parent.right = TreeNode(int(right))
q.append(parent.right)
else:
parent.right = None
return root