当前位置: 代码迷 >> 综合 >> 面试题37 序列化二叉树 python3 BFS+辅助队列
  详细解决方案

面试题37 序列化二叉树 python3 BFS+辅助队列

热度:98   发布时间:2024-02-09 22:49:32.0

请实现两个函数,分别用来序列化和反序列化二叉树。

示例: 

你可以将以下二叉树:

    1
/ \
2   3
/ \
4   5

序列化为 "[1,2,3,null,null,4,5]"

本题的初始代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Codec:def serialize(self, root):"""Encodes a tree to a single string.:type root: TreeNode:rtype: str"""def deserialize(self, data):"""Decodes your encoded data to tree.:type data: str:rtype: TreeNode"""# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))

可见,序列化二叉树输入为一个根节点,输出为一个字符串;反序列化则是字符串输入,能够重建出二叉树。下面分别进行求解。

 

1. 序列化部分

输入:树的根节点;

输出:字符串。

思路

其实这非常像第32题:从上到下打印二叉树 Python3广度优先搜索

首先给出32题的代码。用的是辅助队列+BFS

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution:def levelOrder(self, root: TreeNode) -> List[int]:if not root:return []queue = []res = []queue.append(root)while queue:# for i in queue:node = queue[0]queue = queue[1:]res.append(node.val)if node.left:queue.append(node.left)if node.right:queue.append(node.right)if not queue:return res

对比32题和本题,可以看到,只要在32题的基础上:

  1. 将null的节点也保存到res中(目的是为了完整恢复树):
  2. 整个过程以字符串append的形式完成

就能够得到本题的求解。

总体来说,本题还是使用的层序遍历,具体而言就是BFS+辅助队列的方法。

更改后的代码如下:

代码总是改不对...回去洗澡明天再改