【題目描述】
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'.
設(shè)計(jì)一個(gè)算法猾普,并編寫代碼來序列化和反序列化二叉樹磷蜀。將樹寫入一個(gè)文件被稱為“序列化”,讀取文件后重建同樣的二叉樹被稱為“反序列化”。
如何反序列化或序列化二叉樹是沒有限制的芜壁,你只需要確保可以將二叉樹序列化為一個(gè)字符串碰缔,并且可以將字符串反序列化為原來的樹結(jié)構(gòu)喇颁。
注意: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/
【題目解析】
根據(jù)之前由前序,中序初澎,后序遍歷恢復(fù)二叉樹的經(jīng)驗(yàn)秸应,確定根節(jié)點(diǎn)的位置十分重要(但是這里可能有重復(fù)元素虑凛,故和之前的題目不太一樣)。能直接確定根節(jié)點(diǎn)的有前序遍歷和廣度優(yōu)先搜索软啼,其中較為簡(jiǎn)潔的為前序遍歷桑谍。序列化較為簡(jiǎn)單,但是反序列化的實(shí)現(xiàn)不太容易祸挪。需要借助字符串解析工具锣披。
源碼分析:由二叉樹序列化的過程不難,難就難在根據(jù)字符串進(jìn)行反序列化贿条,這里引入了 Java 中的 StringTokenizer 字符串分割工具雹仿,非常方便,使得遞歸得以順利實(shí)現(xiàn)整以。其中deseriaHelper的實(shí)現(xiàn)較為巧妙胧辽。
【答案鏈接】
http://www.jiuzhang.com/solutions/binary-tree-serialization/