Skip to content

Latest commit

 

History

History
52 lines (38 loc) · 1.51 KB

16. Serialize and Deserialize a Binary Tree.md

File metadata and controls

52 lines (38 loc) · 1.51 KB

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. Now your task is to complete the function serialize which stores the tree into an array A[ ] and deSerialize which deserializes the array to the tree and returns it. Note: The structure of the tree must be maintained. Multiple nodes can have the same data.

image

Link : https://practice.geeksforgeeks.org/problems/serialize-and-deserialize-a-binary-tree/1


Solution :

Time Complexity :

class Tree 
{
    //Function to serialize a tree and return a list containing nodes of tree.
    public void serialize(Node root, ArrayList<Integer> A) 
    {
        if(root==null)
        {
            A.add(-1);
            return;
        } 
        A.add(root.data);
        serialize(root.left,A);
        serialize(root.right,A);
    }

    //Function to deserialize a list and construct the tree.
    public Node deSerialize(ArrayList<Integer> A)
    {
        if(A.get(0)==-1)
        {
            A.remove(0);
            return null;
        }
        Node root = new Node(A.remove(0));
        root.left = deSerialize(A);
        root.right = deSerialize(A);
        return root;
    }
}