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

Posted siriusli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]7. Serialize and Deserialize Binary Tree/[Leetcode]297. Serialize and Deserialize Binary T相关的知识,希望对你有一定的参考价值。

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 T的主要内容,如果未能解决你的问题,请参考以下文章

lintcode - 恢复ip地址

[LintCode] Clone Graph

leetcode297. Serialize and Deserialize Binary Tree

lintcode 132 模式

[Algorithm] 7. Serialize and Deserialize Binary Tree

[LintCode] Container With Most Water 装最多水的容器