Serialize and Deserialize a Binary Tree
Serialization is to store a tree in an array so that it can be later restored and
Deserialization is reading tree back from the array.
Note: The structure of tree must be maintained.
Solution:
- Process in PreOrder and mark null child with special marker (like -1)
Algorithm for serialize:
- Traverse tree in preOrder
- If node is null then,
list.add(-1)
return
list.add(node.data)
- Recursively call node left sub tree
- Recursively call node right sub tree
- If node is null then,
Algorithm for deserialize:
- Create tree in PreOrder
- If counter >= list.size or list.get(counter) == -1 then
return null
- Create node with list.get(counter)
leftSubTree = recursively call with counter + 1
rightSubTree = recursively call with counter + 2
node.left = leftSubTree
node.right = rightSubTree
return node
- If counter >= list.size or list.get(counter) == -1 then
Latest Source Code:
Github: BinaryTreeSerializeAndDeserialize.java
Output:
Binary Tree : 25 / \ / \ / \ / \ / \ / \ / \ / \ 18 50 / \ / \ / \ / \ / \ / \ / \ / \ 19 20 35 60 \ / \ / \ / \ \ / \ / \ / \ 15 18 25 20 40 55 70 \ 25 Serialized Tree :[25, 18, 19, -1, 15, -1, -1, 20, 18, -1, -1, 25, -1, -1, 50, 35, 20, -1, 25, -1, -1, 40, -1, -1, 60, 55, -1, -1, 70, -1, -1] Deserialize Tree : 25 / \ / \ / \ / \ / \ / \ / \ / \ 18 50 / \ / \ / \ / \ / \ / \ / \ / \ 19 20 35 60 \ / \ / \ / \ \ / \ / \ / \ 15 18 25 20 40 55 70 \ 25