...

/

Serialize/Deserialize Binary Tree

Serialize/Deserialize Binary Tree

Given a binary tree, serialize it to a file and then deserialize it back to a tree.

Statement

Serialize a given binary tree to a file and then deserialize it back to a tree. Make sure that the original and the deserialized trees are identical.

  • Serialize: Write the tree in a file.

  • Deserialize: Read from a file and reconstruct the tree in memory.

Example

Consider the below tree as the input tree:

G root 100 node1 50 root->node1 node2 200 root->node2 node3 25 node1->node3 node4 75 node1->node4 node6 350 node2->node6

We’ll serialize our tree into a list of integers, and then we can write this list into a file. For simplicity, we won’t write anything in the files.

Sample input

The input list below represents the level-order traversal of the binary tree:

[100, 50, 200, 25, 75, 350]

Expected output

The sequence below represents the in-order traversal of the deserialized binary tree:

25, 50, 75, 100, 200, 350

Try it yourself

Note: The binary tree node’s class has members left and right to store references to other nodes, along with the member data to hold the node’s value.

main.cpp
BinaryTree.cpp
BinaryTreeNode.cpp
#include <iostream>
#include <vector>
#include <limits>
#include "BinaryTree.cpp"
using namespace std;
vector<int> Serialize(BinaryTreeNode* root) {
// TODO: Write - Your - Code
return {};
}
BinaryTreeNode* Deserialize(vector<int>& stream) {
// TODO: Write - Your - Code
return nullptr;
}

Solution

There can be multiple approaches to serialize and deserialize the tree. One way to serialize the tree is as follows:

  • Perform a depth-first traversal and serialize individual nodes to the stream.

  • We use a pre-order (root, left, right) traversal here.

  • We also serialize the marker to represent a null pointer to help deserialize the tree.

Consider the below binary tree as an example:

G 50 50 25 25 50->25 75 75 50->75 200 200 M5 M5 200->M5 350 350 200->350 M1 M1 25->M1 M2 M2 25->M2 M6 M6 350->M6 M7 M7 350->M7 M3 M3 M4 M4 100 100 100->50 100->200 75->M3 75->M4

Markers (M)(M*) ...