Serialize and Deserialize Binary Tree — LeetCode 297 Python Solution
- Problem
- #297
- Pattern
- Tree Traversal
- Reading time
- 10 min
- Source
- leetcode.com
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
# 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
On study lists
This problem is on Blind 75, NeetCode 150 and Grind 75.
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.