Skip to content

Commit

Permalink
AC. Use Queue. 384ms.
Browse files Browse the repository at this point in the history
  • Loading branch information
rinwf committed Mar 14, 2019
1 parent 07faa64 commit 1e17f14
Showing 1 changed file with 42 additions and 15 deletions.
57 changes: 42 additions & 15 deletions 297. Serialize and Deserialize Binary Tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@

from queue import Queue

class Codec:

class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return ''
lst = []
q = Queue()
q.put(root)
Expand All @@ -27,27 +29,52 @@ def serialize(self, root):
q.put(node.left)
q.put(node.right)
return ','.join(str(x) for x in lst)


def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def construct(lst, idx):
if lst[idx] is None:
return None
node = TreeNode(lst[idx])
left = idx * 2 + 1
right = idx * 2 + 2
if left < len(lst):
node.left = construct(lst, left)
node.right = construct(lst, right)
return node

lst = [int(x) if x.lstrip('-').isdigit() else None for x in data.split(',')]
return construct(lst,0)
if not data:
return None
lst = [
int(x) if x.lstrip('-').isdigit() else None
for x in data.split(',')
]
q = Queue()
root = TreeNode(lst[0])
q.put(root)
length = len(lst)
idx = 0
while not q.empty():
node = q.get()
idx += 1
if idx == length:
break
if lst[idx] is not None:
left = TreeNode(lst[idx])
node.left = left
q.put(left)
idx += 1
if idx == length: break
if lst[idx] is not None:
right = TreeNode(lst[idx])
node.right = right
q.put(right)

return root

# def construct(lst, idx):
# if lst[idx] is None:
# return None
# node = TreeNode(lst[idx])
# left = idx * 2 + 1
# right = idx * 2 + 2
# if left < len(lst):
# node.left = construct(lst, left)
# node.right = construct(lst, right)
# return node


# Your Codec object will be instantiated and called as such:
Expand Down

0 comments on commit 1e17f14

Please sign in to comment.