加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[Lintcode]7. Serialize and Deserialize Binary Tree/[Leetcode

发布时间:2020-12-14 04:24:36 所属栏目:大数据 来源:网络整理
导读:7. Serialize and Deserialize Binary Tree/297. Serialize and Deserialize Binary Tree 本题难度: Medium/Hard Topic: Binary Tree Description Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a f

7. Serialize and Deserialize Binary Tree/297. Serialize and Deserialize Binary Tree

  • 本题难度: Medium/Hard
  • Topic: Binary Tree

Description

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called ‘serialization‘ and reading back from the file to reconstruct the exact same binary tree is ‘deserialization‘.

Example
An example of testdata: Binary tree {3,9,20,#,15,7},denote the following structure:

3
/ 9 20
/ 15 7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

Notice
There is no limit of how you deserialize or serialize a binary tree,LintCode will take your output of serialize as the input of deserialize,it won‘t check the result of serialize.

别人的代码

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self,val):
        self.val = val
        self.left,self.right = None,None
"""


class Solution:
        
    def serialize(self,root):
        def doit(node):
            if node:
                vals.append(str(node.val))
                doit(node.left)
                doit(node.right)
            else:
                vals.append(‘#‘)
        vals = []
        doit(root)
        return ‘ ‘.join(vals)

    def deserialize(self,data):
        def doit():
            val = next(vals)
            if val == ‘#‘:
                return None
            node = TreeNode(int(val))
            node.left = doit()
            node.right = doit()
            return node
        vals = iter(data.split())
        return doit()

思路
使用深度优先遍历,但是要注意占位。

  • 时间复杂度
  • 出错

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读