美文网首页
7. Serialize and Deserialize Bin

7. Serialize and Deserialize Bin

作者: 鸭蛋蛋_8441 | 来源:发表于2019-05-30 13:49 被阅读0次

    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'.

    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.

    Example

    Example 1:

    Input:{3,9,20,#,#,15,7}

    Output:{3,9,20,#,#,15,7}

    Explanation:

    Binary tree {3,9,20,#,#,15,7},  denote the following structure:

      3

    / \

    9  20

      /  \

    15  7

    it will be serialized {3,9,20,#,#,15,7}

    Example 2:

    Input:{1,2,3}

    Output:{1,2,3}

    Explanation:

    Binary tree {1,2,3},  denote the following structure:

      1

      / \

    2  3

    it will be serialized {1,2,3}

    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.

    思路:

    可以用BFS 或者DFS 实现serialization,BFS 需要注意空节点的表示, 在deserialize的时候用了快慢指针,并且用了两个List分别存储全部节点信息以及不包含空节点的信息。DFS用了分治法的思想,代码看起来比较简洁。

    还有一点要注意collections.deque 和queue.Queue()在使用时候的不同,前者可以直接while que后者需要借助 que.empty()

    代码:

    BFS版本的

    DFS的

    相关文章

      网友评论

          本文标题:7. Serialize and Deserialize Bin

          本文链接:https://www.haomeiwen.com/subject/tinmtctx.html