# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
# 导入双向队列
from collections import deque
# 二叉树序列化(对象变Json)
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = []
queue = deque()
queue.append(root)
while queue:
cur = queue.popleft()
if cur:
res.append(cur.val)
queue.append(cur.left)
queue.append(cur.right)
else:
res.append(None)
while res and res[-1]==None:
res.pop()
return res
# 二叉树反序列化(Json变对象)
def deserialize(self, data):
"""Decodes your encoded data to tree
:type data: str
:rtype: TreeNode
"""
data = json.loads(data)
return self.deserialize_res(self, data)
def deserialize_res(self, data):
if len(data) == 0:
return None
root.val = data.pop(0)
root.left = self.deserialize_res(data)
root.right = self.deserialize_res(data)
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
二叉树-序列化与反序列化(利用双向队列实现)
最新推荐文章于 2020-08-27 11:07:36 发布