AcWing 50. 序列化二叉树--Pythonic看我才是正解
原题链接
困难
作者:
roon2300
,
2021-04-13 23:24:52
,
所有人可见
,
阅读 392
- Pythonic写法;
- 支持正负数,浮点数;
- no 递归 no递归 no递归;
- 序列化&反序列化代码非常对称;
- 采用AcWing序列化二叉树的方式;
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root: return '[]'
res = []
q = deque()
q.append(root)
while q:
x = q.popleft()
if x:
res.append(x.val)
q.append(x.left)
q.append(x.right)
else:
res.append(None)
return str(res)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
arr = eval(data)
if not arr: return None
q = deque()
rt = TreeNode(arr[0])
q.append(rt)
i = 1
while q:
x = q.popleft()
if arr[i] is not None:
x.left = TreeNode(arr[i])
q.append(x.left)
if arr[i + 1] is not None:
x.right = TreeNode(arr[i + 1])
q.append(x.right)
i += 2
return rt