博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】297. Serialize and Deserialize Binary Tree
阅读量:7048 次
发布时间:2019-06-28

本文共 2657 字,大约阅读时间需要 8 分钟。

题目如下:

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Example: 

You may serialize the following tree:    1   / \  2   3     / \    4   5as "[1,2,3,null,null,4,5]"

Clarification: The above format is the same as . You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

解题思路:题目对于序列化的格式没有限定,给予了充分发挥的空间。我的方法是把每个节点表示成 节点编号:节点值 这种格式,记根节点的编号为1,那么其左右子节点的编号就是2和3,Example的二叉树序列化之后的结果就是: 1:1;2:2;3:3;6:4;7:5 。

代码如下:

# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Codec:    path = ''    def serialize(self, root):        """Encodes a tree to a single string.        :type root: TreeNode        :rtype: str        """        if root == None:            return ''        self.path = ''        self.recursive(root,1)        return self.path[:-1]    def recursive(self,node,inx):        self.path += str(inx) + ':' + str(node.val) + ';'        if node.left != None:            self.recursive(node.left,2*inx)        if node.right != None:            self.recursive(node.right, 2*inx+1)    def deserialize(self, data):        """Decodes your encoded data to tree.        :type data: str        :rtype: TreeNode        """        print data        if data == '':            return None        itemlist =  data.split(';')        dic = {}        for i in itemlist:            item = i.split(':')            dic[int(item[0])] = int(item[1])        root = TreeNode(dic[1])        queue = [(1,root)]        while len(queue) > 0:            inx,parent = queue.pop(0)            if 2*inx in dic:                l_child = TreeNode(dic[2*inx])                parent.left = l_child                queue.append((2 * inx, l_child))            if 2*inx+1 in dic:                r_child = TreeNode(dic[2*inx+1])                parent.right = r_child                queue.append((2*inx+1, r_child))        return root

 

转载于:https://www.cnblogs.com/seyjs/p/10205544.html

你可能感兴趣的文章
if __name__ == '__main__' :
查看>>
201671010117 2016-2017-2 《Java程序设计》Java第三周学习心得
查看>>
颜色区分
查看>>
微信认证结果拆分为资质审核和名称审核
查看>>
Sass和Compass入门
查看>>
ionic + cordova 使用 cordova-gallery-api 获取本地相册所有图片
查看>>
重装系统后删除Cygwin文件夹
查看>>
享元模式
查看>>
M4修改外部晶振8M和25M晶振的方法
查看>>
六、python小功能记录——递归删除bin和obj内文件
查看>>
持续集成~Jenkins构建dotnetCore的项目
查看>>
EF架构~数据分批批量提交
查看>>
MVC+LINQToSQL的Repository模式系列~目录
查看>>
信号和槽:Qt中最差劲的创造
查看>>
design_model(1)singleton
查看>>
leetcode Majority Element
查看>>
treap模板
查看>>
vue组件通信之任意级组件之间的通信
查看>>
bootstrap2.02 notice
查看>>
Android Fragment的使用(1)
查看>>