这个题有些bug,但还是一道ok的题目。给一颗二叉树,可以将其序列化,并且还原回树。这也是一种压缩或者表示的手段。注意:叶子节点的后面跟着None。而这两种方法都可以用bfs解决。
序列化时,我们可以用bfs,如果是None,就不入队,否则入队,然后不断让儿子入队,最终完成。
解码时,我们需要遍历数组,不断地将数组赋给父节点。由于每个父亲最多两个儿子,就按顺序给就行,代码如下:
from queue import Queue
# 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 []
l = []
q = Queue()
q.put(root)
while not q.empty():
e = q.get()
if e:
l.append(e.val)
q.put(e.left)
q.put(e.right)
else: l.append(None)
return l
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if data == []: return None
root = TreeNode(data[0])
q = Queue()
q.put(root)
i = 1
while i < len(data):
c = q.get()
if data[i] == None: c.left = None
else:
c.left = TreeNode(data[i])
q.put(c.left)
i += 1
if data[i] == None: c.right = None
else:
c.right = TreeNode(data[i])
q.put(c.right)
i += 1
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))