Skip to content

Commit

Permalink
recursive solution
Browse files Browse the repository at this point in the history
  • Loading branch information
rinwf committed Mar 14, 2019
1 parent 1e17f14 commit 932c5d4
Showing 1 changed file with 12 additions and 54 deletions.
66 changes: 12 additions & 54 deletions 297. Serialize and Deserialize Binary Tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
# self.left = None
# self.right = None

from queue import Queue


class Codec:
def serialize(self, root):
Expand All @@ -16,65 +14,25 @@ def serialize(self, root):
:rtype: str
"""
if not root:
return ''
lst = []
q = Queue()
q.put(root)
while not q.empty():
node = q.get()
if not node:
lst.append(None)
continue
lst.append(node.val)
q.put(node.left)
q.put(node.right)
return ','.join(str(x) for x in lst)
return '# '
return str(root.val) + ' ' + self.serialize(root.left) + self.serialize(root.right)

def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
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
def des():
val = next(it)
if val == '#':
return None
node = TreeNode(int(val))
node.left = des()
node.right = des()
return node
it = iter(data.split())
return des()


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

0 comments on commit 932c5d4

Please sign in to comment.