297. Serialize and Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
Method 1 Breadth-First Search (BFS)
Serialize
BFS uses queue to realize. queue : First In First Out (FIFO). Following is the step by step algorithm.
- Enqueue root node into the queue. Check the front of the queue.
- If front == “null”, return “null”.
sr3. If front != “null”, push the node value into a stringstream. - Enqueue the left and right childs into the queue.
- Dequeue the current node.
- Loop until the queue is empty.
Code
1 | // Encodes a tree to a single string. |
Deserialize
Except the first one is the value of the root node, the other node values are paired, corresponding to the left and right child nodes.
- Convert the input string to a vector list.
- Traverse list, connecting the nodes in order of “left child, right child, left child, right child, …”
Code
1 | TreeNode* deserialize(string data) { |