码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-02-14 23:57:27      阅读:302      评论:0      收藏:0      [点我收藏+]

标签:treenode   val   cal   wing   design   next   when   follow   des   

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()

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

  • 时间复杂度
  • 出错

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

标签:treenode   val   cal   wing   design   next   when   follow   des   

原文地址:https://www.cnblogs.com/siriusli/p/10381199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!