algorithm - 使用左/右括号序列化和反序列化树
问题描述
这里的树有 n 个节点(不是二叉树!)
我试图实现以下的想法
1 (1((2)(3)(4)))
/ \ \
2 3 4
(2) (3) (4)
我的初始算法起草如下。序列化函数是在每次调用时返回(
根子(
节点。))
反序列化函数是从括号中构造根及其子节点
有人可以看到为什么实施不正确吗?
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
if not root: return ''
if not root.children: return '(' + str(root.val) + ')'
res = "("
for child in root.children:
res += self.serialize(child)
res += ')' # ((2)(3)(4))
return '(' + str(root.val) + res + ')' # (1((2)(3)(4)))
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: Node
"""
# ^
# 0 1 2 3 ...
# ( 1 ( ( 2 )(3) ) )
if not data: return None
val = data[1]
root = Node(int(val))
root.children = []
left = 0
start = 3 # choose 3 as shown above(skip all parenthesis until seeing the children)
for i in range(3, len(data) - 2): #skip last parentheses for the same reason
if data[i] == '(': left += 1
if data[i] == ')':
left -= 1
if left == 0:
child = self.deserialize(data[start:i + 1])
root.children.append(child)
start = i + 1
return root
解决方案
推荐阅读
- python - 使用 ModuleDict,我有:输入类型(torch.cuda.FloatTensor)和权重类型(torch.FloatTensor)应该相同
- c++ - 标准::复杂
乘以其他类型 - python-3.x - 从 CSV 文件下载图像
- c++ - 关于对象引用的混淆
- javascript - 对象中最后一行后的尾随逗号
- angular - 两种不同类型的数据
- algorithm - 如何解决 BST 问题?
- azure - 是否可以从 Microsoft.Azure.EventHubs 库迁移到 Azure.Messaging.EventHubs 而不会丢失检查点?
- java - 如何将 HashMap 数据保存在我电脑的任何位置?
- ms-access - 在 MS Access 的 Format 函数中使用变量时,数字的格式不正确