Skip to main content

Serialize and Deserialize Binary Tree - Solution & Explanation

HardStringTreeDepth-First SearchBreadth-First Search23 min readAsked at: Amazon, Microsoft, Apple +20
Practice this problem

Problem Statement

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

 

Example 1:

Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]

Example 2:

Input: root = []
Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 <= Node.val <= 1000

Approach Overview

Problem Overview: Design two functions: one converts a binary tree into a string (serialize), and the other reconstructs the same tree from that string (deserialize). The structure of the tree must remain identical after reconstruction, including null children.

Approach 1: Depth‑First Search Serialization (Preorder) (Time: O(n), Space: O(n))

This approach performs a preorder traversal: visit the current node, then the left subtree, then the right subtree. During serialization, append node values to a string and insert a special marker such as # for null children. The key insight is that preorder traversal combined with explicit null markers uniquely represents the tree structure. During deserialization, read tokens sequentially and rebuild the tree recursively: create a node for a value and recursively construct its left and right children. Every node and null placeholder is processed exactly once, giving O(n) time and O(n) space for recursion and storage. This method is common when working with Depth-First Search on a Binary Tree.

Approach 2: Breadth‑First Search Serialization (Level Order) (Time: O(n), Space: O(n))

This approach uses level-order traversal with a queue. During serialization, push the root into a queue and process nodes level by level. Append each node's value to the output string, and insert a placeholder such as # when a child is missing. For deserialization, read the values sequentially and reconstruct the tree by attaching left and right children while dequeuing parent nodes. The queue ensures nodes are connected in the same order they appeared in the level traversal. This method mirrors how many tree problems are solved using Breadth-First Search, and it often feels more intuitive because it directly follows the tree’s level structure.

Both strategies rely on encoding null nodes explicitly. Without null markers, different trees could produce identical serialized sequences, making reconstruction impossible.

Recommended for interviews: The preorder DFS approach is the most common expectation. It demonstrates clear understanding of tree traversal, recursion, and structural encoding. The BFS approach also runs in O(n) time and is equally valid, but interviewers usually prefer the recursive preorder method because the serialization and deserialization logic aligns naturally with tree structure.

Approach 1: Using HashMap for Counting Elements

This approach involves using a HashMap (or dictionary in Python) to count the occurrences of each element in the array. This will help in efficiently checking if an element exists and how many times it appears, which is useful for problems requiring frequency analysis.

This C solution uses an array to simulate a hash table where each index represents an element and its value represents the frequency. This allows both insertion and lookup to occur in constant O(1) time.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), as it iterates over the array once. Space Complexity: O(1) if the element range is known and constant, or O(k) where k is the range of elements.

Try this approach in the editor →

Approach 2: Using Sorting to Identify Repeated Elements

Another approach is sorting the array and then identifying repeated elements by comparison with neighboring elements. This leverages the efficiency of modern sorting algorithms to bring repeated elements together, making it trivial to count consecutive duplicates.

This C solution sorts the input array using quicksort and then counts consecutive elements to tally occurrences. Sorting ensures similar elements cluster together, thus simplifying frequency determination.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n) due to the sort operation. Space Complexity: O(1) if in-place sorting is considered.

Try this approach in the editor →

Approach 3: Level Order Traversal

We can use level order traversal to serialize the binary tree. Starting from the root node, we add the nodes of the binary tree to the queue in the order from top to bottom, from left to right. Then we dequeue the nodes in the queue one by one. If the node is not null, we add its value to the serialized string; otherwise, we add a special character #. Finally, we return the serialized string.

During deserialization, we split the serialized string by the delimiter to get a string array, and then add the elements in the string array to the queue in order. The elements in the queue are the nodes of the binary tree. We dequeue the elements from the queue one by one. If the element is not #, we convert it to an integer and use it as the value of the node, and then add the node to the queue; otherwise, we set it to null. Finally, we return the root node.

The time complexity is O(n), and the space complexity is O(n). Where n is the number of nodes in the binary tree.

Code

Python

Java

C++

Go

JavaScript

C#

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Using HashMap for Counting Elements

Time Complexity: O(n), as it iterates over the array once. Space Complexity: O(1) if the element range is known and constant, or O(k) where k is the range of elements.

Using Sorting to Identify Repeated Elements

Time Complexity: O(n log n) due to the sort operation. Space Complexity: O(1) if in-place sorting is considered.

Level Order Traversal—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
DFS Preorder SerializationO(n)O(n)Preferred interview solution; simple recursive reconstruction of tree structure
BFS Level Order SerializationO(n)O(n)Useful when thinking in level traversal or implementing iterative queue-based logic

Video Solution

Serialize and Deserialize Binary Tree - Preorder Traversal - Leetcode 297 - Python • NeetCode • 170,759 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Serialize and Deserialize Binary Tree easy or hard?
Serialize and Deserialize Binary Tree is classified as a Hard problem on LeetCode. The difficulty comes from designing a reversible encoding scheme that preserves the full tree structure, including null children.
Serialize and Deserialize Binary Tree Python/Java solution
Python and Java implementations typically use preorder traversal with a delimiter-separated string and a null marker such as '#'. Deserialization reads tokens sequentially and recursively reconstructs the tree. Both languages achieve O(n) time and O(n) space complexity.
How to solve Serialize and Deserialize Binary Tree in O(n)?
Traverse the tree using preorder DFS and record values in a string while inserting a special marker like # for null nodes. During reconstruction, read the sequence sequentially and recursively build left and right children. Each node and placeholder is processed once, resulting in O(n) time.
What is the best approach for Serialize and Deserialize Binary Tree?
Preorder depth-first traversal with null markers is the most common solution. The tree is serialized by visiting nodes in preorder and writing a placeholder for missing children. During deserialization, the same order allows recursive reconstruction of the exact structure in O(n) time.
Is Serialize and Deserialize Binary Tree asked at Google/Amazon/Meta?
Serialize and Deserialize Binary Tree frequently appears in interviews at companies like Google, Amazon, Meta, and Microsoft. The problem tests tree traversal, recursion design, and the ability to encode and reconstruct data structures.
What data structure is used in Serialize and Deserialize Binary Tree?
The main data structures include binary trees, recursion stacks, queues for BFS solutions, and strings or arrays to store serialized values. DFS solutions rely on recursive calls, while BFS implementations use a queue for level-order traversal.
What is the time complexity of Serialize and Deserialize Binary Tree?
Both serialization and deserialization run in O(n) time where n is the number of nodes in the tree. Each node is processed exactly once, and null placeholders are handled in constant time operations.

Ready to solve this problem?

Practice Serialize and Deserialize Binary Tree with our built-in code editor and test cases.

Practice on FleetCode