Java Program to Serialize and Deserialize a Binary Tree

This Java program demonstrates the serialization and deserialization of a binary tree. Serialization is the process of converting a tree into a string format which can be easily stored or transmitted, and deserialization reconstructs the tree from this string representation.

Binary Tree and Serialization Classes

The BinaryTree class includes methods to serialize the tree into a string and deserialize the string back into the tree structure using pre-order traversal.

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class BinaryTree {
    static class Node {
        int data;
        Node left, right;

        public Node(int data) {
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }

    Node root;

    // Serialize the binary tree to a string
    public String serialize(Node root) {
        if (root == null) {
            return "null,";
        }
        String serialized = root.data + ",";
        serialized += serialize(root.left);
        serialized += serialize(root.right);
        return serialized;
    }

    // Deserialize the string back to the binary tree
    public Node deserialize(String data) {
        Queue<String> nodes = new LinkedList<>(Arrays.asList(data.split(",")));
        return deserializeHelper(nodes);
    }

    private Node deserializeHelper(Queue<String> nodes) {
        String val = nodes.poll();
        if (val.equals("null")) {
            return null;
        }
        Node node = new Node(Integer.parseInt(val));
        node.left = deserializeHelper(nodes);
        node.right = deserializeHelper(nodes);
        return node;
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);

        String serialized = tree.serialize(tree.root);
        System.out.println("Serialized tree: " + serialized);

        Node deserializedRoot = tree.deserialize(serialized);
        System.out.println("Tree deserialized successfully");
    }
}

Explanation of Serialization and Deserialization Methods

  • serialize – This method uses a pre-order traversal to convert the tree into a comma-separated string of node values, using “null” for absent children to preserve the tree structure.
  • deserialize – Converts the string back into a tree by recursively processing the node values from a queue which ensures that each node is recreated in the correct order.

Conclusion

The provided Java implementation effectively serializes a binary tree into a string and deserializes it back to the tree structure. This process is crucial for storing trees in databases, sending them over networks, or simply for persistent storage.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)