×

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a file again.

When a binary search tree is provided, we can save it by either storing preorder traversal or postorder traversal. Only preorder or postorder traversal is necessary and sufficient in the case of Binary Search Trees to store structure data.

If the given binary tree is a Complete Binary Tree, the following must be done. All the levels of a binary tree must be fully filled, with the exception of the last level, and all of the last level's nodes must be as far to the left as feasible (Binary Heaps are complete Binary Tree). Level order traversal is sufficient to store a whole binary tree. The first node is the root, the following two are nodes of the following level, the following four are nodes of the following level, and so on.

If the given binary tree is a Full Binary Tree, the following must be done. A full binary tree is one that has either 0 or 2 children at each node. Since every internal node has two offspring, such trees are simple to serialise. Preorder traversal can be easily stored, and we can also include a bit with each node to specify whether it is an internal node or a leaf node.

Storing a general Binary Tree:

Storing both Inorder and Preorder traversals is an easy fix. The space needed for this solution is twice as large as for Binary Tree. Preorder traversal and a marker for NULL pointers can be stored in less space.

An assumption is to be made which is indicating a NULL pointer with -1.

Consider the following examples

Input:

Serialize and Deserialize Binary Trees

Output: 123 146 -1 -1 -1

So, in the above example, the elements are stored accordingly in the Depth First Search manner.

Input:

Serialize and Deserialize Binary Trees

Output: 30 18 -1 -1 32 -1 -1

Input:

Serialize and Deserialize Binary Trees

Output: 30 18 3 -1 -1 12 11 -1 15 -1 -1 -1 32 -1 -1

Input:

Serialize and Deserialize Binary Trees

Output: 30 -1 32 -1 4 -1 8 -1 -1

These are few examples of how the elements of the binary tree are stored in the file during the serialization process.

// An example Java programme for serialising and deserializing Binary Trees.


import java.util.*;
 
/* 
A TreeNode is created which has a value, pointer to the left child and a pointer to the right child.
 */


class BTreeNode {
    int data;
    BTreeNode left;
    BTreeNode right;
    BTreeNode(int x) 
    { 
data = x; 
    }
} // BTreeNode
 
// A class for the binary tree is created. 


class BinaryTreeDemo {
    BTreeNode root;
 
    // A Tree is given to a single string.
    public static String serialize (BTreeNode root)
    {
	//Checking if the given tree is empty or not.
        if (root == null) {
            return null;
        }
	//A stack of datatype BTreeNode is created.
        Stack<BTreeNode> st = new Stack<>();
        st.push(root);	//Root element is added to the stack.
 
	// An arraylist which can take string parameters is created.


        List<String> list = new ArrayList<>();
        while (!s.isEmpty()) {
            BTreeNode t = st. pop ();
            // A marker is stored, if the current node is NULL.


            if (t == null) {
                list.add("#");
            }
            else {
                /*
If the current node is not NULL, then store the current node and recur for its children.
                */
                list.add ("" + t.data);
                st. push(t.right);
                st. push(t.left);
            }
        }
        return String.join (",", l);
    }
 
    static int temp;
 
    // This part of code decodes the data which is encoded.
    public static BTreeNode deserialize (String val)
    {
        if (val == null)
            return null;
        temp = 0;
        String [] array = val.split (",");
        return helper(array);
    }
 
    public static BTreeNode helper (String [] array)
    {
        if (array [temp]. equals ("#"))
            return null;
        // A node is created having its item and can recur for its children.
        BTreeNode root
            = new BTreeNode (Integer.parseInt (array[temp]));
        temp++;
        root.left = helper(array);
        temp++;
        root.right = helper(array);
        return root;
    }
 
    // A Inorder traversal to test the constructed tree.


    static void Inorder (BTreeNode root)
    {
        if (root != null) {
            Inorder (root.left);
            System.out.print(root.data + " ");
            Inorder(root.right);
        }
    }
 
    /* 
     Driver code for the above Methods.
    */


    public static void main (String args[])
    {
        // Now let’s construct a binary tree.


        BinaryTreeDemo btree = new BinaryTreeDemo();
        btree.root = new BTreeNode(30);
        btree.root.left = new BTreeNode(18);
        btree.root.right = new BTreeNode(32);
        btree.root.left.left = new BTreeNode(14);
        btree.root.left.right = new BTreeNode(22);
        btree.root.left.right.left = new BTreeNode(20);
        btree.root.left.right.right = new BTreeNode(24);
 
        String serialize = serialize (btree.root);
        System.out.println ("The view of the tree after serialization:");
        System.out.println(serialize);
        System.out.println();
 
        // Now let’s perform deserialization.


        BTreeNode tp = deserialize (serialize);
 
        System.out.println(
            "The Inorder Traversal of the binary tree which is constructed from serialized String is:");
        Inorder(tp);
    } // main
} // BinaryTreeDemo

If there are n keys, then the preceding technique needs n+1 markers, which may be preferable to the straightforward solution (storing keys twice) in cases where keys are large or have substantial data items attached to them.

Optimization:

There are numerous approaches to optimise the previous solution. A deeper inspection of the serialised trees shown above reveals that every leaf node needs two markers. To store a distinct bit with each node to indicate whether it is internal or external is a straightforward optimization. In this method, since leaves can be distinguished by an extra bit, we don't need to store two markers with each leaf node. Marker for internal nodes with a single child is still required.


Related Topics

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Find out the area between two concentric circles

You have given two values of the radius of two circles. You have to find out the area between these two circles. Let's take an example - For the above diagram,...

3 minutes read.

Common Operations on various Data Structures

Data structures are ways to organise data in computer memory for quick and effective use. The storage of data uses a variety of data-structures. It is also possible to define...

7 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Segregate Even and Odd nodes in a Linked List

Segregate even and odd nodes in a Linked List In this problem, we have given a linked list with integer numbers. We need to modify the given linked list in such...

4 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

Queue operations in Data Structure

Queue - Queue is a linear data structure or first in first out data structure means the first element added in the queue will be removed first and the last...

7 minutes read.

CSS Text-indent

Text-indent The Text-indent property of CSS is used to set any first line’s indentation inside a text’s block. It describes the horizontal space amount that puts establish before the text line. It...

3 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

3 minutes read.

Height of a binary tree

The height of a binary tree is generally defined as the height or length of the root _nod in the entire binary tree. In simple words, the height of a...

4 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

10 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 minutes read.

Difference Between Linear and Non Linear Data Structures

Data Structure A data structure is a data object together with the relationships between the instances and the individual elements that compose an instance. These relationships are defined by the operations...

5 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

19 minutes read.

Sorting Algorithms

Sorting: In the data structure, sorting is the process by which you arrange the data in a logical order. This logical order can also be an ascending order or a...

7 minutes read.