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
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Convert a given Binary tree to a tree that holds Logical AND property
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Sub-tree with minimum color difference in a 2-coloured tree
- Create a mirror tree from the given binary tree
- Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
- Convert a Binary Tree into its Mirror Tree
- Minimum swap required to convert binary tree to binary search tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach