Serialize and Deserialize N-ary Tree Problem
Description
LeetCode Problem 428.
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize an N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that an N-ary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following 3-ary tree

as [1 [3[5 6] 2 4]]. Note that this is just an example, you do not necessarily need to follow this format.
Or you can follow LeetCode's level order traversal serialization format, where each group of children is separated by the null value.

For example, the above tree may be serialized as [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14].
You do not necessarily need to follow the above-suggested formats, there are many more different formats that work so please be creative and come up with different approaches yourself.
Example 1:
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Example 2:
Input: root = [1,null,3,2,4,null,5,6]
Output: [1,null,3,2,4,null,5,6]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 10^4]. 0 <= Node.val <= 10^4- The height of the n-ary tree is less than or equal to
1000 - Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
Solution
Approach: Level Order with End-of-Children Markers
Writing just the values is not enough to rebuild the tree, because nodes have different numbers of children. A list of values does not say where one node's children stop and the next node's start. The fix is to add a marker, #, after each node's list of children. This is the same idea as the null separators in LeetCode's own format.
serialize. Write the root's value and put the root in a queue. Then, while the queue is not empty, take the next node, write the values of all its children (adding each child to the queue), and write #. Join everything with commas. For Example 2 this gives 1,3,2,4,#,5,6,#,#,#,#,#: node 1 has children 3, 2, 4; node 3 has 5, 6; and nodes 2, 4, 5 and 6 have none.
deserialize. Split on commas. Make the root from the first token and put it in a queue. Take nodes from the queue in the same order: for each one, every token up to the next # is a new child, which goes into the queue as well. Then skip the #.
Both sides take nodes from their queues in the same order, so the k-th group of tokens before a # always belongs to the k-th node taken from the queue. The empty tree is the empty string, and that case is checked first, because "".split(",") returns one empty token. The work is iterative, so a tree 1000 levels deep is not a problem. Nothing is stored in the Codec object between calls, as the problem requires.
Complexity: O(n) time for both serialize and deserialize, where n is the number of nodes. O(n) space for the queue and the string.
import collections
class Codec:
def serialize(self, root: 'Node') -> str:
"""Level order: the root, then for each node its children's values followed by "#"."""
if root is None:
return ""
out = [str(root.val)]
queue = collections.deque([root])
while queue:
node = queue.popleft()
for child in node.children or []:
out.append(str(child.val))
queue.append(child)
out.append("#") # end of this node's children
return ",".join(out)
def deserialize(self, data: str) -> 'Node':
if not data:
return None
tokens = data.split(",")
root = Node(int(tokens[0]), [])
queue = collections.deque([root])
i = 1
while queue:
node = queue.popleft() # the next tokens up to "#" are its children
while tokens[i] != "#":
child = Node(int(tokens[i]), [])
node.children.append(child)
queue.append(child)
i += 1
i += 1 # skip the "#"
return root