-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path297_SerializeandDeserializeBinaryTree.py
More file actions
46 lines (40 loc) · 1.15 KB
/
297_SerializeandDeserializeBinaryTree.py
File metadata and controls
46 lines (40 loc) · 1.15 KB
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
# 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
"""
def helper(node):
if node:
res.append(str(node.val))
helper(node.left)
helper(node.right)
else:
res.append('#')
res = []
helper(root)
return ','.join(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def helper():
val = next(res)
if val == '#':
return None
node = TreeNode(int(val))
node.left = helper()
node.right = helper()
return node
res = iter(data.split(','))
return helper()
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))