0
点赞
收藏
分享

微信扫一扫

剑指offer-python:34.序列化二叉树

有态度的萌狮子 2022-02-04 阅读 155

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

你需要设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。

 

序列化:BFS

反序列化:也是BFS,在序列化中,空节点用‘null’表示。外加一个index一步一步+1即可。

代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class erchashu():
    def serialize(self,root):
        if not root:return '[]'
        res , queue = [] , []
        queue.append(root)
        while queue:
            new_node = queue.pop(0)  # BFS使用队列方式
            res.append(new_node.val)
            if new_node:
                queue.append(new_node.left)
                queue.append(new_node.right)
            else:
                res.append('null')
        return '[' + ','.join(res) + ']'

    def deserialize(self , data):
        if len(data) == 0:return None
        new_list = data.split(']')[0].split('[')[1].split(',')
        root , index = TreeNode(int(new_list[0])),1
        queue = [root]
        while queue:
            node = queue.pop(0)  # 同BFS
            if new_list[index] != 'null':
                node.left = TreeNode(int(new_list[index]))
                queue.append(node.left)
            index += 1
            if new_list[index] != 'null':
                node.right = TreeNode(int(new_list[index]))
                queue.append(node.right)
            index += 1
        return root
举报

相关推荐

0 条评论