[
tree
parser
stack
string
]
Leetcode 0428. Serialize and Deserialize N-ary Tree
Problem statement
https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/
Solution
One possible solution is to use Preorder Serialization, similar what we did in problems 0297 and 0331. For example for our example tree, serialization looks like 1 3 5 # 6 # # 2 # 4 #
. We use preoder traversal and when we go back, we add #
symbol.
Complexity
Complexity is $O(n)$ both for serialization and deserialization (using stack), where $n$ is number of nodes.
Code
class Codec:
def serialize(self, root):
def recur(node):
result.append(str(node.val))
for neib in node.children:
recur(neib)
result.append("#")
if not root: return "#"
result = []
recur(root)
return ' '.join(result)
def deserialize(self, data):
if len(data) == 1:
return None
data = data.split()
root = Node(int(data[0]), [])
stack = [root]
for elem in data[1:]:
if elem == "#":
stack.pop()
else:
New_node = Node(int(elem), [])
stack[-1].children += [New_node]
stack.append(New_node)
return root
Remark
Possible other solutions are to use brackets as it suggested and write parser for brackets.