449. Serialize and Deserialize BST
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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.
The encoded string should be as compact as possible.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
My 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 not root:
return ''
str_list = []
self.get_str(root, str_list)
return '#'.join(str_list)
def get_str(self, root, str_list):
if not root:
return
str_list.append(str(root.val))
self.get_str(root.left, str_list)
self.get_str(root.right, str_list)
def deserialize(self, data): # data = self.serialize(root)
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if data == '':
return None
value_list = data.split('#')
root = TreeNode(int(value_list[0]))
for value in value_list[1:]:
self.insertBST(root, node=TreeNode(int(value)))
return root
def insertBST(self, root, node):
if node.val < root.val:
if root.left:
return self.insertBST(root.left, node)
else:
root.left = node
if node.val > root.val:
if root.right:
return self.insertBST(root.right, node)
else:
root.right = node
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
Reference:
用deque代替List:
# 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):
vals = []
def preOrder(node):
if node:
vals.append(node.val)
preOrder(node.left)
preOrder(node.right)
preOrder(root)
return ' '.join(map(str, vals))
# O( N ) since each val run build once
def deserialize(self, data):
vals = collections.deque(int(val) for val in data.split())
def build(minVal, maxVal):
if vals and minVal < vals[0] < maxVal:
val = vals.popleft()
node = TreeNode(val)
node.left = build(minVal, val)
node.right = build(val, maxVal)
return node
return build(float('-infinity'), float('infinity'))
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))