428. Serialize and Deserialize N-ary Tree
Asked at Apple, TikTok
Difficulty
Hard
Time
O(n)
Space
O(n)
Pattern
String
Companies
2
Problem
Design two functions for an N-ary tree (a rooted tree where each node can have any number of children). serialize(root) turns the tree into a single string. deserialize(data) takes that string and rebuilds the exact same tree.
The format of the string is up to you. The only hard rule is round-trip correctness: deserialize(serialize(root)) must give back a tree with the same shape and the same values. The empty tree must also survive the round trip.
A clean way to do this is a pre-order DFS. For each node, write its value, then write how many children it has, then recurse into the children in order. For a missing node, write a special marker such as #. Because the child count is stored right next to the value, the decoder always knows exactly how many subtrees to read next — no guessing, no ambiguity. Your functions must be stateless: do not keep data in class members, globals or static variables between calls.
One tree, one string, and back again
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 or static variables to store state; serialize and deserialize must be stateless.
Examples
root = [1,null,3,2,4,null,5,6][1,null,3,2,4,null,5,6]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][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]root = [][]Asked At
2 companies| Company | Difficulty | |
|---|---|---|
| Apple | Hard | View all Apple questions → |
| TikTok | Hard | View all TikTok questions → |
How to Think About It
Brute force: Use BFS with a delimiter to separate node values and track null markers for missing children at each level.
Improved: Use DFS with a special marker like "#" to represent null nodes and a count of children before each node value.
Better: Encode each node as "value,count" and recursively serialize children, using "#" for null subtrees.
Refined: Pre-order DFS traversal where you write the node value, then the number of children, then recurse into each child.
Optimal: Pre-order DFS with "value count" format separated by spaces. Write node count before children to handle variable branching without ambiguity.
Optimal Approach
The optimal approach uses a pre-order DFS traversal. For each node, write its value followed by the number of children, then recursively process each child. For null nodes, write "#" as a marker. During deserialization, read tokens one by one: if the token is "#", return null. Otherwise, parse the value and child count, create the node, then recursively deserialize each child. This produces an unambiguous encoding because the child count tells the deserializer exactly how many subtrees to expect. Both operations run in O(n) time and use O(n) space for the output string and recursion stack.
Pre-order DFS: value, child count, then children
Solution Code
O(n) timeclass Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children or []
class Codec:
def serialize(self, root):
parts = []
def dfs(node):
if not node:
parts.append("#")
return
parts.append(str(node.val))
parts.append(str(len(node.children)))
for child in node.children:
dfs(child)
dfs(root)
return " ".join(parts)
def deserialize(self, data):
tokens = iter(data.split())
def dfs():
token = next(tokens)
if token == "#":
return None
val = int(token)
count = int(next(tokens))
node = Node(val)
node.children = [dfs() for _ in range(count)]
return node
return dfs()Frequently Asked Questions
What is the Serialize and Deserialize N-ary Tree problem?
Design an algorithm to serialize and deserialize an N-ary tree to a string and back. Unlike binary trees, each node can have zero or more children, requiring a different encoding strategy to capture the variable branching structure.
How do you solve Serialize and Deserialize N-ary Tree?
The optimal approach runs in O(n) time and O(n) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.
What companies ask Serialize and Deserialize N-ary Tree?
Serialize and Deserialize N-ary Tree is asked at Apple, TikTok. It is a hard difficulty problem.