Serialize and Deserialize a Binary Tree

Published: 07 May 2016
on channel: IDeserve
33,232
456

Given a binary tree, how can you serialize and deserialize it?

Serialization: Storing a given tree in a file or in an array.
Deserialization: Reverse of serialization.

Serialization is done using pre-order traversal -
A pre-order traversal array is created by visiting the tree in Root Node-Left subtree-Right subtree style in recursive manner.
We write a special marker ‘-1’ whenever a null node is encountered.

--------------

For Deserialization, following algorithm is used -

int index = 0;

Node deserialize(ArrayList array)
{
if (index == array.size() || array.get(index) == -1)
{
index += 1;
return null;
}

Node root = new Node(array.get(index));
index += 1;

root.left = deserialize(array);
root.right = deserialize(array);

return root;
}

Time Complexity: O(n)
Space Complexity: O(n)

Website: http://www.ideserve.co.in

Facebook:   / ideserve.co.in  


On this page of the site you can watch the video online Serialize and Deserialize a Binary Tree with a duration of hours minute second in good quality, which was uploaded by the user IDeserve 07 May 2016, share the link with friends and acquaintances, this video has already been watched 33,232 times on youtube and it was liked by 456 viewers. Enjoy your viewing!