Serialize And Deserialize Binary Tree Problem
Description
LeetCode Problem 297.
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: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [1,2]
Constraints:
- The number of nodes in the tree is in the range [0, 10^4].
- -1000 <= Node.val <= 1000
Solution
Approach: Level-Order Traversal (BFS)
The node values alone do not pin down the shape of a tree, so the string also records where children are missing, with a # marker. Then the tree can be rebuilt in the same order it was written.
serialize: write the root's value, then visit the nodes level by level with a queue. For each node taken from the queue, write its left child and then its right child: the child's value, or # if there is none. Real children go into the queue. The tree [1,2,3,null,null,4,5] becomes
1,2,3,#,#,4,5,#,#,#,#
deserialize: split on commas, create the root from the first value, and replay the same process. Take the next node from the queue; the next two entries of the string are its left and right child. Create a node for each value that is not # and add it to the queue. Each node in the queue reads exactly two entries, in the same order serialize wrote them, so the reconstruction matches node for node.
Two details:
- The empty tree has to be handled on both sides. Here it is the empty string.
- Values can be negative and have several digits, so separate them with commas instead of reading one character per value.
This is iterative, so a very deep tree (a chain of thousands of nodes) does not risk a stack overflow, which a recursive preorder version can.
Complexity: O(n) time and O(n) space for both serialize and deserialize, where n is the number of nodes.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Codec:
# Level order: the root's value, then both children of every node in queue order,
# with "#" for a missing child. [1,2,3,null,null,4,5] becomes "1,2,3,#,#,4,5,#,#,#,#".
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if root is None:
return ""
parts = [str(root.val)]
queue = collections.deque([root])
while queue:
node = queue.popleft()
for child in (node.left, node.right):
if child is None:
parts.append("#")
else:
parts.append(str(child.val))
queue.append(child)
return ",".join(parts)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if data == "":
return None
parts = data.split(",")
root = TreeNode(int(parts[0]))
queue = collections.deque([root])
i = 1 # the next part to read: the left, then the right child of the node in front
while queue:
node = queue.popleft()
if parts[i] != "#":
node.left = TreeNode(int(parts[i]))
queue.append(node.left)
if parts[i + 1] != "#":
node.right = TreeNode(int(parts[i + 1]))
queue.append(node.right)
i += 2
return root
Now write it from memory
Close the write-up and solve it yourself against the tests.