LeetCode Serialize and Deserialize Binary Tree (Java)

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.

For example, you may serialize the following tree

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.


Based on the hint, we can use the same method of how LeetCode OJ serializes a binary tree to serialize a binary tree based on the idea of level order tree traversal. 

For example, the above tree will result in this string S = "1,2,3,null,null,4,5"

In the deserialization stage, we know the first element (1) is the root of the tree. The second element (2) is the root’s left child, denoted as rootLeft, the third element (3) is the root’s right child, denoted as rootRight. Then the following two elements are the left and right child of the node rootLeft

If we process the elements in S one by one. In the first step, we can easily create the root Node (e.g, root = new TreeNode(1)). 

Then we scan the remaining elements in S, and use the first two elements (e.g. 2 and 3) to build the left and right child of root

Then we come to the 4th and 5th element (both are null). We know they are the children of rootLeft, but how can we get the reference of rootLeft when we encounter the 4th and 5th element in S?

We can use a Queue to store rootLeft as soon as it is created. So when we encounter the 4th and 5th element in S, we just poll the head of the queue, which is rootLeft

See the following code for how we use queue in the deserialization stage.