-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy path0297.py
35 lines (32 loc) · 907 Bytes
/
0297.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
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = ""
def postOrder(root):
nonlocal res
if not root:
res += '# '
return
postOrder(root.left)
postOrder(root.right)
res += str(root.val) + ' '
postOrder(root)
return res
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
datas = data.split()
def deOrder():
val = datas.pop()
if val == '#':
return
root = TreeNode(int(val))
root.right = deOrder()
root.left = deOrder()
return root
return deOrder()