Problem: https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/
Use preorder traversal to dump the given tree. To make the deserialize process simpler, we dump the size of children list after the node value to indicate how many children node is needed under current node.
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
def preorder(node):
yield str(node.val)
yield str(len(node.children))
for nxt in node.children:
yield from preorder(nxt)
return ','.join(preorder(root)) if root else ''
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree.
:type data: str
:rtype: Node
"""
data = data.split(',') if data else []
def helper(index):
if index >= len(data):
return None, index
node = Node(val=int(data[index]), children=[])
index += 1
size = int(data[index])
index += 1
for _ in range(size):
child, index = helper(index)
node.children.append(child)
return node, index
return helper(0)[0]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
No comments:
Post a Comment