一种基于前序遍历的解法。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import Queue
# 本解法是基于层次遍历的。序列化和反序列化中的队列中都会有None,但是循环时读到None时不会读它的左右节点。另外可以参考水中的鱼的前序遍历解法:
# http://fisherlei.blogspot.jp/2013/03/interview-serialize-and-de-serialize.html
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
if root is None:
return ''
list = []
list.append(root)
i = 0
# 优化的层次遍历,不使用Queue,直接使用一个list存储和遍历。
while i < len(list):
if list[i] is not None:
list.append(list[i].left)
list.append(list[i].right)
i += 1
# 将list打印成逗号分隔的字符串
res_str = ''
for j in range(len(list)):
if list[j] is not None:
res_str += str(list[j].val) + ','
else:
res_str += 'x' + ','
return res_str[0:-1]
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if data == '':
return None
input = data.split(',')
root = TreeNode(input[0])
q = Queue.Queue(-1)
q.put(root)
i = 0
# 逻辑是使用队列循环节点,然后有一个计数器,如果节点不是'x',则计数器加2
while q.qsize() > 0 and i + 2 < len(input):
node = q.get()
if node.val != 'x':
i += 1
left = TreeNode(input[i])
if left.val != 'x':
node.left = left
q.put(left)
i += 1
right = TreeNode(input[i])
if right.val != 'x':
right = TreeNode(input[i])
node.right = right
q.put(right)
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))