AlgoMaster Logo

Serialize and Deserialize Binary Tree

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. BFS with Queue

Intuition:

This approach uses a queue to perform a level-order traversal (BFS) to serialize and deserialize a binary tree. The BFS approach processes nodes level by level, which suits the serialization of nodes where it can record the tree's structure, including null children, by utilizing a delimiter.

Serialize:

  1. Start: Initialize a queue and add the root to it.
  2. Traverse: While the queue is not empty:
    • Dequeue an element. If it is not null, add its value to the result string and enqueue its children. If it is null, add a special marker (e.g., "null") to the result string.
  3. Output: Join all results with a comma.

Deserialize:

  1. Start: Split the serialized string on commas and initialize a queue.
  2. Initialize: Create the root node and add it to the queue.
  3. Reconstruct: For each node, check its children from the serialized data:
    • If it is "null", move to the next node.
    • Otherwise, create a new node, link it as a child, and add it to the queue.

Code:

2. DFS with Preorder Traversal

Intuition:

In this approach, the idea is to use a depth-first search (DFS) technique with a recursive method that uses preorder traversal. This involves capturing each node followed by its left and right children. By marking null references explicitly, reconstruction is facilitated.

Serialize:

  1. Use a recursive function to append node values to a StringBuilder in preorder (root → left → right).
  2. Append a special marker ("null") for null nodes to denote absent children.
  3. Join all elements to generate the final serialized string.

Deserialize:

  1. Split the serialized data using a delimiter.
  2. Use recursive functions to construct tree nodes in preorder, consuming values sequentially:
    • Return null when a "null" string is found.
    • Create a tree node using the current value and recursively handle its left and right subtrees.

Code: