# LeetCode: 297. 二叉树的序列化与反序列化¶

## 1、题目描述¶

你可以将以下二叉树：

1
/ \
2   3
/ \
4   5



• 说明: 不要使用类的成员 / 全局 / 静态变量来存储状态，你的序列化和反序列化算法应该是无状态的。

## 2、解题思路¶

• 使用层级标号法
使用下面的形式表示一棵树：
根节点{level}左子树{level}右子树


# 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
"""

def dfs(node, level):
mark = "{" + str(level) + "}"

if not node:
return mark * 2
left = dfs(node.left, level + 1)
right = dfs(node.right, level + 1)

return str(node.val) + mark + left + mark + right

return dfs(root, 0)

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

:type data: str
:rtype: TreeNode
"""

def dfs(d, level):
mark = "{" + str(level) + "}"
current, left, right = d.split(mark)
if not current:
return None

node = TreeNode(int(current))
node.left = dfs(left, level + 1)
node.right = dfs(right, level + 1)
return node

return dfs(data, 0)

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