HardNo. 0297

Serialize and Deserialize Binary Tree — LeetCode 297 Python Solution

Topics
Tree, Depth-First Search, Breadth-First Search, Design, String, Binary Tree
On study lists
Blind 75, NeetCode 150 and Grind 75
Reading time
10 min

The problem

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.

Example

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

Python solution

PythonSolution
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Codec:
    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        if root is None:
            return ""
        q = deque([root])
        ans = []
        while q:
            node = q.popleft()
            if node:
                ans.append(str(node.val))
                q.append(node.left)
                q.append(node.right)
            else:
                ans.append("#")
        return ",".join(ans)

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        if not data:
            return None
        vals = data.split(",")
        root = TreeNode(int(vals[0]))
        q = deque([root])
        i = 1
        while q:
            node = q.popleft()
            if vals[i] != "#":
                node.left = TreeNode(int(vals[i]))
                q.append(node.left)
            i += 1
            if vals[i] != "#":
                node.right = TreeNode(int(vals[i]))
                q.append(node.right)
            i += 1
        return root


# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 297. Serialize and Deserialize Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0449Serialize and Deserialize BSTMedium
0100Same TreeEasy
0101Symmetric TreeEasy
0104Maximum Depth of Binary TreeEasy
0111Minimum Depth of Binary TreeEasy
0112Path SumEasy

Frequently asked questions

How hard is LeetCode 297. Serialize and Deserialize Binary Tree?

LeetCode 297. Serialize and Deserialize Binary Tree is rated Hard on LeetCode.

What is the time complexity of LeetCode 297. Serialize and Deserialize Binary Tree?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 297. Serialize and Deserialize Binary Tree?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 297. Serialize and Deserialize Binary Tree cover?

LeetCode 297. Serialize and Deserialize Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search, Design, String and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.