• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Contact Us

All about code

  • Java
    • Spring
      • Spring Boot
      • Spring Cloud
    • Java Miscellaneous Tips
    • Java Design Patterns
  • Data Structures and Algorithms
    • Algorithms
    • Data Structures
  • Thoughts and Stories
  • AI

Serialize and Deserialize a Binary Tree: Easy Explanation

laptop infographic online business 6087062

Introduction

Serialize and Deserialize a Binary Tree is essential for tasks such as saving the tree’s state, sending it over a network, or storing it in a file. Serialization converts the tree into a string representation, while deserialization reconstructs the tree from this string.

Problem Statement

The goal is to implement two functions: one to serialize a binary tree into a string and another to deserialize the string back into the original tree structure. This is particularly useful when dealing with distributed systems or persistent storage.

Approach

A common way to serialize a tree is using a pre-order traversal (root, left, right). During serialization, we also need to record null children to preserve the tree’s structure. We’ll use a delimiter (like a comma) to separate node values and a placeholder (e.g., “null”) for missing nodes.

During deserialization, we’ll reverse the process. By reading values in pre-order, we rebuild the tree recursively.

Java Implementation

Below is a complete Java implementation using pre-order traversal.

//Unique class name for serialization and deserialization of binary trees
public class BinaryTreeCodec {

 // Converts a binary tree into a string representation
 public String encode(TreeNode root) {
     StringBuilder output = new StringBuilder();
     encodeTree(root, output);
     return output.toString();
 }

 private void encodeTree(TreeNode current, StringBuilder output) {
     if (current == null) {
         output.append("#,");
         return;
     }
     output.append(current.val).append(",");
     encodeTree(current.left, output);
     encodeTree(current.right, output);
 }

 // Restores a binary tree from its string representation
 public TreeNode decode(String data) {
     Queue<String> nodeValues = new LinkedList<>(Arrays.asList(data.split(",")));
     return decodeTree(nodeValues);
 }

 private TreeNode decodeTree(Queue<String> nodeValues) {
     if (nodeValues.isEmpty()) return null;

     String value = nodeValues.poll();
     if ("#".equals(value)) return null;

     TreeNode node = new TreeNode(Integer.parseInt(value));
     node.left = decodeTree(nodeValues);
     node.right = decodeTree(nodeValues);

     return node;
 }
}

//Tree node structure
class TreeNode {
 int val;
 TreeNode left;
 TreeNode right;

 TreeNode(int value) {
     this.val = value;
 }
}

Example Usage

Here’s how you can use the Codec class to serialize and deserialize a tree.

javaCopiaModificapublic class Main {
    public static void main(String[] args) {
        Codec codec = new Codec();

        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(5);

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

        TreeNode deserialized = codec.deserialize(serialized);
        System.out.println("Deserialized Root: " + deserialized.val);
    }
}

Conclusion

Serialization and deserialization of binary trees are key for data storage and transmission. By using pre-order traversal and handling nulls carefully, you can faithfully convert a tree to a string and back without losing structure or data.

You can find the example code on Github.

Primary Sidebar

Social

  • Facebook
  • LinkedIn
  • Twitter

Archives

  • May 2026
  • April 2026
  • March 2026
  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • December 2024
  • October 2024
  • August 2024
  • July 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • September 2023
  • May 2023
  • March 2023
  • January 2023
  • November 2022
  • September 2022
  • August 2022

Recent Posts

  • Better Avoid Spring Boot Lazy-initialization @PostConstruct Trap
  • How To Handle Large Datasets in Spring Boot
  • How to Log HTTP Incoming Requests in Spring Boot
  • How to Reliably Implement Post-Commit Actions in Spring
  • Brief and Easy Explanation of HATEOAS

TAGS

Algorithms Apache POI Backtracking Date Structures Dynamic Programming engineering Graphs Greedy Horror Stories HSSF Java Java New Features Java Principles Java tips real life Sorting Spring Boot Spring Cloud Strings Trees

Footer

Privacy Policy Cookie Policy Terms and Conditions