Interview Questions

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. 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