-
Notifications
You must be signed in to change notification settings - Fork 178
/
39_SerializeTree.py
38 lines (36 loc) · 1.03 KB
/
39_SerializeTree.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
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 序列化
def Serialize(self, root):
retList = []
def preOrder(root):
if root == None:
# 找到为空的节点,插入 #
retList.append("#")
return None
# 否者插入该节点
retList.append(str(root.val))
preOrder(root.left)
preOrder(root.right)
preOrder(root)
return ' '.join(retList)
# 反序列化
def Deserialize(self, s):
retList = s.split(" ")
if retList == None:
return None
def dePreOrder():
rootVal = retList.pop(0)
if rootVal == "#":
return None
node = TreeNode(rootVal)
leftNode = dePreOrder()
rightNode = dePreOrder()
node.left = leftNode
node.right = rightNode
return node
return dePreOrder()