# 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
"""
vals = []
def encode(root):
if not root:
vals.append('null')
return
vals.append(str(root.val))
encode(root.left)
encode(root.right)
encode(root)
return '[' + ','.join(vals) + ']'
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
vals = iter(data[1:-1].split(','))
def decode():
val = next(vals)
if val == 'null':
return
node = TreeNode(val)
node.left = decode()
node.right = decode()
return node
return decode()