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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Serialize and Deserialize a Binary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Convert a Generic Tree(N-array Tree) to Binary Tree
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
- Difference between General tree and Binary tree
- Difference between Binary Tree and Binary Search Tree
- Difference between Binary tree and B-tree
- Difference between B tree and B+ tree
- Convert a given Binary tree to a tree that holds Logical AND property
- Convert a Binary Tree into its Mirror Tree
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Check if a binary tree is subtree of another binary tree | Set 1
- Convert a given tree to its Sum Tree
- Binary Tree to Binary Search Tree Conversion
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not