forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize.py
More file actions
26 lines (20 loc) · 761 Bytes
/
serialize.py
File metadata and controls
26 lines (20 loc) · 761 Bytes
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
class Codec:
def serialize(self, root):
preorder = []
def helper(node):
if node:
preorder.append(node.val)
helper(node.left)
helper(node.right)
helper(root)
return ' '.join(map(str, preorder))
def deserialize(self, data):
vals = collections.deque(int(val) for val in data.split())
def build(minval, maxval):
if vals and minval < vals[0] < maxval:
val = vals.popleft()
node = TreeNode(val)
node.left = build(minval, val)
node.right = build(val, maxval)
return node
return build(float('-infinity'), float('infinity'))