美文网首页Lintcode程序员
Lintcode7 Binary Tree Serializat

Lintcode7 Binary Tree Serializat

作者: 代码码着玩 | 来源:发表于2017-03-19 15:50 被阅读36次

    【题目描述】

    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.

    【题目链接】

    http://www.lintcode.com/en/problem/binary-tree-serialization/

    【题目解析】

    根据之前由前序,中序,后序遍历恢复二叉树的经验,确定根节点的位置十分重要(但是这里可能有重复元素,故和之前的题目不太一样)。能直接确定根节点的有前序遍历和广度优先搜索,其中较为简洁的为前序遍历。序列化较为简单,但是反序列化的实现不太容易。需要借助字符串解析工具。

    源码分析:由二叉树序列化的过程不难,难就难在根据字符串进行反序列化,这里引入了 Java 中的 StringTokenizer 字符串分割工具,非常方便,使得递归得以顺利实现。其中deseriaHelper的实现较为巧妙。

    【答案链接】

    http://www.jiuzhang.com/solutions/binary-tree-serialization/

    相关文章

      网友评论

        本文标题:Lintcode7 Binary Tree Serializat

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