Serialize And Deserialize A Given N-Ary Tree

Serialize And Deserialize A Given N-Ary Tree

Serialize And Deserialize A Given N-Ary Tree Rating: 8,9/10 919 votes

Problem

LeetCode Question: Serialize and Deserialize Binary Tree Serialize and Deserialize Binary Tree Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another.

For a binary tree class containing integer values, we want to write a pair of serialization and deserialization function. As a reminder, serialization is the process of taking an object and converting is into bytes, usually for either sending the data over the network or for storing it on disk. Many programming languages, like Java, offer some default serialization, but those are usually not human-readable.

N-ary tree using linked list

Algorithm

For serialization, the easiest way is to go through the tree breadth-first and serializing the values as we go. The matching deserialization algorithm needs to reconstruct the tree from the result of the serialization algoritm. Since values are in breadth-first order, deserialization will follow a similar strategy as serialization, keeping a queue containing the nodes from the previous level in order to rebuild the current level.
In terms of data structures, using a StringBuilder for serialization is recommended, as it allows efficient append. For the breadth-first search part, we obviously need a queue.

Code

This problem can be found on leetcode and career cup.

161. How to serialize and deserialize a n-ary tree?

Microsoft Interview Questions and Answers

(Continued from previous question..)

161. How to serialize and deserialize a n-ary tree?

Question:
How to serialize and deserialize a n-ary tree?
maybe an answer2:
//Serialize the tree.Writing the tree values to a file or array is serialization.
//Storing the data from the tree in an array. Enterprise architect 9 full crack. or we can store the node itself in an object array.We have to
//design accordingly.
public void Serialize(Node root,ref int []treeArray,ref int index)
{
if (root null)
{
treeArray[index++] = -999;
}
else
{
treeArray[index++] = root.ID;
Serialize(root.Left, ref treeArray, ref index);
Serialize(root.Right, ref treeArray, ref index);
}
}
//DESerialize the tree.Creating the tree from the data stored in the file or array.
public Node DeSerialize(ref int[] treeArray, ref int index,int arrayCount)
{
if (treeArray[index] -999 && index < arrayCount)
{
index++;
return null;
}
else
{
Node node = new Node();
node.ID = treeArray[index++];
node.Left = DeSerialize(ref treeArray, ref index,arrayCount);
node.Right = DeSerialize(ref treeArray,ref index,arrayCount);
return node;
}
}
//Complexity is O(n)

(Continued on next question..)

Other Interview Questions

Serialize And Deserialize A Given N-Ary Tree
© 2020