Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/51/
Topics
Design an algorithm to serialize and deserialize a binary tree.
Explanation: Serialization means that some specific structure in memory becomes a string of formatted information. For example, for a linked list, we can serialize a list of 1->2->3->null such as "All-in-a-kind." For serialization algorithms, deserialization must be supported, and in the agreed format, strings that meet the format requirements can be reconstructed to the desired structure. In this scenario, you need to implement both a serialization function and a deserialization function.
Online test
http://lintcode.com/problem/serialization-and-deserialization-of-binary-tree/
Answer
Use BFS. For the following two-pronged tree:
1
/ \
2 3
/ \
4 5
The BFS sequence is: [1,2,3,4,5]. If we show the left and right son of the leaf node with #, we can get the following tree:
1
/ \
2 3
/ \ / \
# # 4 5
/ \ / \
# # # #
One line to see can be: [1,2,3,#,#,4,5,#,#,#,#]
By removing the trailing #, you can get [1,2,3,#,#,4,5], which is done using BFS to serialize.
Similarly, we can also use DFS for serialization, the result of DFS serialization is as follows: [1,2,#,#,3,4,#,#,5,#,#], minus the end of the # to get [1,2,#,#,3,4,#,#,5], than BFS serialization results are longer. The main reason is that most of the # appears at the bottom, so the BFS way can make as many # as possible in the tail of the serialization.
The process of deserialization, there is no more explanation.
Interviewer Angle
The so-called serialization is to turn a structured thing into a flattened string. This allows for easy transmission and compression. The use of BFS or Dfs method is correct in the interview, but if can compare the method of BFS can more effectively save space, you can get extra points.
Nine-chapter algorithm surface test 512 the serialization of the fork Tree