leetcode-mid-design-297. Serialize and Deserialize Binary Tree¶-NO -??
2024-10-07 05:43:04
mycode
将list转换成树的时候没有思路
参考:
deque 是双边队列(double-ended queue),具有队列和栈的性质,在 list 的基础上增加了移动、旋转和增删等
class Codec: def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode
:rtype: str
"""
vals = []
def preOrder(root):
if not root:
vals.append('#')
else:
vals.append(str(root.val))
preOrder(root.left)
preOrder(root.right)
preOrder(root)
return ' '.join(vals) def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str
:rtype: TreeNode
"""
vals = collections.deque(val for val in data.split())
def build():
if vals:
val = vals.popleft()
if val == '#':
return None
root = TreeNode(int(val))
root.left = build()
root.right = build()
return root
return build() # Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
其中queue可以用list替换
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str
:rtype: TreeNode
"""
print(data)
self.vals = [val for val in data.split()]
print(self.vals)
def build():
if self.vals:
val = self.vals[0]
self.vals = self.vals[1:] if val == '#':
return None
root = TreeNode(int(val))
root.left = build()
root.right = build()
return root
return build()
疑惑
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str
:rtype: TreeNode
"""
print(data)
vals = [val for val in data.split()]
print(self.vals)
def build():
if vals:
val = vals[0]
vals[:] = vals[1:]
print(vals)
if val == '#':
return None
root = TreeNode(int(val))
root.left = build()
root.right = build()
return root
return build()
Line 35: AttributeError: Codec instance has no attribute 'vals'
最新文章
- 判断浏览器类型用 document.documentMode方式,
- Exynos 4412
- 优秀的技术Leader
- ADO.NET 增 删 改 查
- css-高度自适应的问题(body高度问题)
- PacBio软件总览 - 初级分析
- 不会JS中的OOP,你也太菜了吧!(第二篇)
- 一个网站的head和body是如何进行优化的
- Win7关机出现关闭程序提示框
- 《C和指针》章节后编程练习解答参考——第10章
- IOS--UISlider的使用方法
- ENOVIA 基础
- 回归 WordPress
- c语言基础学习02
- bzoj 2820 莫比乌斯反演
- ActiveMQ的断线重连机制
- 金融量化分析【day110】:IPython介绍及简单操作
- login_code
- Cache架构设计
- php上传图片预览,放大,裁剪