Serialize and Deserialize Binary Tree

Given a binary tree, write a code to serialize and deserialize binary tree.

You can choose any algorithm for serialization and deserialization of a binary tree. But make sure the algorithm we choose to serialize a binary tree to a string and can also deserialize the string representation to the original tree structure.

What is serialization and deserialization?

Before solving this problem, let’s first understand what is serialization and deserialization?

In Serialization, the data structure or object is translated/converted into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network.

Deserialization is the process to reconstruct the data structure or object from the sequence of bits.

Range Sum of BST

Let’s discuss a problem range sum of BST (binary search tree).

In this problem, given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].

Binary Search Tree (BST)

In binary search tree, the value of all the nodes in the left sub-tree is less than the value of the root node. Similarly, Value of all the nodes in the right sub-tree is greater than or equal to the value of the root.

For example

In the below example (image), we have to find the sum of all nodes whose value lies in the range of 7 to 15 (inclusive).

The nodes 7, 10, and 15 lie in this range and its sum is 32.