Lintcode7 Binary Tree Serialization solution 題解

【題目描述】

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/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章