BFS
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
"""
首刷
"""
class Codec:
"""
BFS 遍历
"""
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if not root:
return ""
queue = [root]
result = []
for node in queue:
if node:
result.append(str(node.val))
queue.append(node.left)
queue.append(node.right)
else:
result.append("#")
return "@".join(result)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if len(data) == 0:
return None
result = data.split("@")
root = TreeNode(int(result[0]))
count = 1
queue = [root]
for node in queue:
#列表已经遍历完了
if count >= len(result):
break
#左边
if result[count] != "#":
tmp_int = int(result[count])
left = TreeNode(tmp_int)
node.left = left
queue.append(left)
count += 1
#右边
if result[count] != "#":
tmp_int = int(result[count])
right = TreeNode(tmp_int)
node.right = right
queue.append(right)
count += 1
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))