AcWing 50. 序列化二叉树--python-DFS与栈模拟
原题链接
困难
作者:
zc2077
,
2020-07-10 12:00:51
,
所有人可见
,
阅读 557
DFS
- idea:以传tuple的形式分割左右子树与根结点;
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return "."
left = self.serialize(root.left)
right = self.serialize(root.right)
s = (left, right, root.val)
return s
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if not data or data[-1] == '.': return None
left, right, val = data
root = TreeNode(val)
root.left = self.deserialize(left)
root.right = self.deserialize(right)
return root
栈模拟
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return []
q = [root]
res = []
while q:
node = q.pop(0)
if not node:
res.append('null')
else:
res.append(node. val)
q.append(node.left)
q.append(node.right)
return res
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if len(data) == 0: return None
if data[0] =='null': return None
root = TreeNode(data.pop(0))
q = [root]
LF = True
while data:
tmp = data.pop(0)
if tmp != 'null':
node = TreeNode(tmp)
q.append(node)
if LF:
q[0].left = node
else:
q[0].right = node
if not LF:
q.pop(0)
LF = not LF
return root