This repository has been archived by the owner on Jul 30, 2020. It is now read-only.
forked from alqamahjsr/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 5
/
428_Serialize_and_Deserialize_N-ary_Tree.py
67 lines (53 loc) · 2 KB
/
428_Serialize_and_Deserialize_N-ary_Tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
# Idea: preorder recursive traversal; add number of children after root val, in order to know when to terminate.
# Example: The example in description is serialized as: "1,3,3,2,5,0,6,0,2,0,4,0"
# Ref: https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/discuss/151421/Java-preorder-recursive-solution-using-queue/169724
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
nodeList = []
self.serializeHelper(root, nodeList)
# print('Serialized Input: ', ','.join(map(str, nodeList)))
return ','.join(map(str, nodeList))
def serializeHelper(self, root, nodeList):
if root is None:
return
nodeList.append(root.val)
nodeList.append(len(root.children))
for child in root.children:
self.serializeHelper(child, nodeList)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: Node
"""
if len(data) <= 0:
return None
nodeList = data.split(",")
indexs = [0]
deserializedData = self.deserializeHelper(nodeList, indexs)
# print('Deserialized Output: ', deserializedData)
return deserializedData
def deserializeHelper(self, nodeList, indexs):
if indexs[0] == len(nodeList):
return None
root = Node(int(nodeList[indexs[0]]), [])
indexs[0] += 1
childrenSize = int(nodeList[indexs[0]])
indexs[0] += 1
for index in range(childrenSize):
root.children.append(self.deserializeHelper(nodeList, indexs))
# print('root.children: ', root.children)
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))