首页 > 其他 > 详细

6.16

时间:2020-06-16 22:38:51      阅读:65      评论:0      收藏:0      [点我收藏+]

每日一题:二叉树的序列化与反序列化 https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        res = ‘‘
        if not root:
            return res
        node_pool = [root]
        res = str(root.val)
        while node_pool:
            tmp = []
            for node in node_pool:
                if not node.left:
                    res += ‘,‘ + ‘null‘
                else:
                    res += ‘,‘ + str(node.left.val)
                    tmp.append(node.left)
                if not node.right:
                    res += ‘,‘ + ‘null‘
                else:
                    res += ‘,‘ + str(node.right.val)
                    tmp.append(node.right)
            node_pool = tmp
        print(res)
        return res

    def deserialize(self, data):
        if not data:
            return None
        str_set = data.split(‘,‘)
        res = TreeNode(int(str_set[0]))
        node_pool = [res]
        ptr = 1
        nums = 2
        while ptr < len(str_set):
            child_pool = []
            child_set = str_set[ptr:ptr + nums]
            for i, node in enumerate(node_pool):
                if child_set[2 * i] != ‘null‘:
                    node.left = TreeNode(int(child_set[2 * i]))
                    child_pool.append(node.left)
                if child_set[2 * i + 1] != ‘null‘:
                    node.right = TreeNode(int(child_set[2 * i + 1]))
                    child_pool.append(node.right)
            ptr += nums
            nums = 2 * len(child_pool)
            node_pool = child_pool
        return res

  

6.16

原文:https://www.cnblogs.com/2014slx/p/13149467.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!