Given an N-ary tree where every node has at-most N children. How to serialize and deserialze it? Serialization is to store tree in a file so that it can be later restored. The structure of tree must be maintained. Deserialization is reading tree back from file.
This post is mainly an extension of below post.
Serialize and Deserialize a Binary Tree
In an N-ary tree, there are no designated left and right children. An N-ary tree is represented by storing an array or list of child pointers with every node.
The idea is to store an ‘end of children’ marker with every node. The following diagram shows serialization where ‘)’ is used as end of children marker.
Following is C++ implementation of above idea.
Constructed N-Ary Tree from file is A B E F K C D G H I J
The above implementation can be optimized in many ways for example by using a vector in place of array of pointers. We have kept it this way to keep it simple to read and understand.
This article is contributed by varun. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Serialize and Deserialize a Binary Tree
- Serialize and Deserialize array of string
- jQuery | serialize() with Examples
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Convert a given Binary tree to a tree that holds Logical AND property
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Tournament Tree (Winner Tree) and Binary Heap
- Two Dimensional Binary Indexed Tree or Fenwick Tree
- Sub-tree with minimum color difference in a 2-coloured tree
- Binary Indexed Tree or Fenwick Tree
- Convert a Binary Tree into its Mirror Tree