Serialize and Deserialize N-ary Tree
Master this topic with zero to advance depth.
Serialize and Deserialize N-ary Tree
N-ary tree.
Level I: BFS (Level Order with null markers)
Intuition
In an N-ary tree, we can use a marker (like null) to distinguish between the children of different parents. During serialization, we use a queue and for every node, we add its children followed by a null to indicate the end of that node's children list.
Logic
- Serialize: Queue based BFS. Append
nullafter children of each node. - Deserialize: Use two queues or pointers to rebuild.
Detailed Dry Run
Node 1 children: [3, 2, 4]. Serialized: [1, null, 3, 2, 4, null, 5, 6, null...]
Level II: DFS (with Parentheses)
Intuition
We can represent the tree structure using parentheses: 1(3(5,6),2,4). This is a very intuitive human-readable format.
Logic
- Serialize:
node.val+(+ serialize(child) for each child +). - Deserialize: Use a stack to track parent nodes and nested parentheses.
Detailed Dry Run
Tree: 1 -> [3, 2, 4]. 3 -> [5, 6]. Serial: 1(3(5,6),2,4).
Level III: Optimal (DFS with Child Count)
Intuition
To serialize an N-ary tree, we can use DFS (Preorder). For each node, we record its value and the number of children it has. During deserialization, we read the value, create a node, and then recursively deserialize exactly count children for that node.
Logic
- Serialization: Append
valandchildren.size(). - Deserialization: Read
val, readsize, then loopsizetimes to build child subtrees.
Detailed Dry Run
| Node | Children | Serialized Array |
|---|---|---|
| 1 | 3 | [1, 3] |
| 3 | 2 | [1, 3, 3, 2] |
| 5 | 0 | [1, 3, 3, 2, 5, 0] |
| 6 | 0 | [1, 3, 3, 2, 5, 0, 6, 0] |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.