Serialize and Deserialize a Binary Tree | Practice | GeeksforGeeks

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.
Example 1:
Input:
      1
    /   \
   2     3
Output: 2 1 3

Example 2:
Input:
         10
       /    \
      20    30
    /   \
   40  60
Output: 40 20 60 10 30

Your Task:
The task is to complete two function serialize which takes the root node of the tree as input and stores the tree into an array and deSerialize which deserializes the array to the original tree and returns the root of it.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of nodes <= 1000
1 <= Data of a node <= 1000

Note: The Input/Ouput format and Example given above are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console, and should not print anything on stdout/console. The task is to complete the function specified, and not to write the full code.
 
+1
amishasahu3283 weeks ago
class Solution
{
    public:
    //Function to serialize a tree and return a list containing nodes of tree.
    vector<int> ans;
    vector<int> serialize(Node *root) 
    {
        //Your code here
        if(root == NULL)
        {
            ans.push_back(-1);
            return ans;
        }
        
        ans.push_back(root->data);
        serialize(root->left);
        serialize(root->right);
        
        return ans;
    }
    
    //Function to deserialize a list and construct the tree.
    int i = 0;;
    Node * deSerialize(vector<int> &A)
    {
       //Your code here
       if(i == A.size()) return NULL;
       int val = A[i];
       i++;
       if(val == -1) return NULL;
       
       Node *root = new Node(val);
       root->left = deSerialize(A);
       root->right = deSerialize(A);
       return root;
    }

};
0
abiradb981 month ago
C++ Solution(0.0s)
class Solution
{
    public:
    //Function to serialize a tree and return a list containing nodes of tree.
    vector<int> serialize(Node *root) 
    {
        //Your code here
        vector<int> res;
        queue<Node*> q;
        q.push(root);
        
        while (!q.empty()) {
            Node* curr = q.front();
            q.pop();
            
            if (!curr) {
                res.push_back(-1);
            }
            else {
                res.push_back(curr->data);     
                q.push(curr->left);
                q.push(curr->right);
            }
        }
        
        return res; 
    }
    
    
    //Function to deserialize a list and construct the tree.
    Node * deSerialize(vector<int> &A)
    {
       //Your code here
       Node* root = new Node(A[0]);
       queue<Node*> q;
       q.push(root);
       int index = 1;
       
       while (!q.empty()) {
           Node* curr = q.front();
           q.pop();
           
           int newN = A[index++];
           if (newN == -1) {
               curr->left = NULL;
           }
           else {
               curr->left = new Node(newN);
               q.push(curr->left);
           }
           
           newN = A[index++];
           if (newN == -1) {
               curr->right = NULL;
           }
           else {
               curr->right = new Node(newN);
               q.push(curr->right);
           }
       }
       return root;
    }

};
0
adityagagtiwari1 month ago
Hi! Can anyone help me in getting rid of the static variable t in the following code.
Even though this code works fine i want to know if there is any way to remove the static variable without harming the functionality of the code
class Tree {   //Function to serialize a tree and return a list containing nodes of tree.public void serialize(Node root, ArrayList<Integer> A) {    //code here    if(root==null)    return;    Stack<Node> stk = new Stack<>();    stk.push(root);    while(stk.size()>0)    {        Node removed = stk.pop();        if(removed==null)        {            A.add(-1);        }        else        {            A.add(removed.data);            stk.push(removed.right);            stk.push(removed.left);        }    }     System.out.println(A);    }//Function to deserialize a list and construct the tree.static int t ;   public Node deSerialize(ArrayList<Integer> A)   {       //code here       //int t=0;       t=0;       Node root = newDeserial(A);       return root;   }   public Node newDeserial(ArrayList<Integer> A)   {       if(A.get(t)==-1)       return null;       Node root = new Node(A.get(t));       t++;      root.left = newDeserial(A);      t++;       root.right = newDeserial(A);       return root;   }   };
+1
codecrackerp2 months ago
vector<int> serialize(Node *root) 
   {   
        vector<int>a;
        if (root==NULL){
          a.push_back(0);
          return a;
        }
        queue<Node*>q;
        q.push(root);
        while(!q.empty()){
            Node*frnt=q.front();
            q.pop();
            if(frnt==NULL){
                a.push_back(0);
            }
            else{
                a.push_back(frnt->data);
                q.push(frnt->left);
                q.push(frnt->right);
            }
        }
        return a;
   }
   
   //Function to deserialize a list and construct the tree.
   Node*Create_Node(int Data){
       if(Data==0)return NULL;
       Node*newnode=new Node(Data);
       return newnode;
   }
   Node * deSerialize(vector<int> &A)
   {   
       int i=0;
       if(A[i]==0){
           return NULL;
       }
       Node*root=Create_Node(A[i++]);
       queue<Node*>q;
       q.push(root);
       while(!q.empty()){
           Node*frnt=q.front();
           q.pop();
           frnt->left=Create_Node(A[i++]);
           frnt->right=Create_Node(A[i++]);
           if(frnt->left!=NULL)q.push(frnt->left);
           if(frnt->right!=NULL)q.push(frnt->right);
       }
       return root;
   }
+2
arvindchoudhary62902 months ago
class Solution
{
    public:
   
    
    //Function to serialize a tree and return a list containing nodes of tree.
    vector<int> serialize(Node *root) 
    {
        vector<int> nodes;
        if(root == NULL) return nodes;
        
        queue<Node*> q;
        q.push(root);
        while(!q.empty())
        {
            Node* currentnode = q.front();
            q.pop();
            
            if(currentnode == NULL)
            {
                nodes.push_back(-1);
            }
            else
            {
                nodes.push_back(currentnode->data);
            }
            if(currentnode!=NULL)
            {
                q.push(currentnode->left);
                q.push(currentnode->right);
            }
        }
        return nodes;
        
    }
    
    
    Node * deSerialize(vector<int> &A)
    {
       if(A.size() == 0) return NULL;
       
       int i=0;
        Node* root = new Node(A[i]);
       i++;
       queue<Node*> q;
       q.push(root);
       
       while(!q.empty())
       {
           Node* node = q.front();
           q.pop();
           
           if(A[i] == -1)
           {
               node->left = NULL;
               i++;
           }
           else
           {
               Node* leftnode = new Node(A[i]);
               node->left = leftnode;
               q.push(leftnode);
               i++;
           }
           if(A[i] == -1)
           {
               node->right = NULL;
               i++;
           }
           else
           {
               Node* rightnode = new Node(A[i]);
               node->right = rightnode;
               q.push(rightnode);
               i++;
           }
       }
       return root;
       
       
       
       
       
       
    }

};
+2
vishnu12653 months ago
Java Solution:
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;
        
        
        
    }
}
+4
abhixhek053 months ago
/* Using preorder traversal to store data in vector and storing -1 when there is NULL /*


class Solution
{
    public:
    
    void func1(Node* root,vector<int> &ans){
        if(root==NULL){ans.push_back(-1); return;}
        ans.push_back(root->data);
        func1(root->left, ans);
        func1(root->right, ans);
        
    }
    //Function to serialize a tree and return a list containing nodes of tree.
    vector<int> serialize(Node *root) 
    {
        //Your code here
        vector<int> ans;
        func1(root, ans);
        return ans;
    }
    
    //Function to deserialize a list and construct the tree.
    int i=0;
    Node * deSerialize(vector<int> &A)
    {
       //Your code here
       if(i==A.size()) return NULL;
    int val = A[i];
    i++;
    if(val==-1) return NULL;
    Node* root = new Node(val);
    
       root->left = deSerialize(A);
        root->right = deSerialize(A);
        return root;
        
    }

};

+1
kalamarham3 months ago
class Solution{   public:   //Function to serialize a tree and return a list containing nodes of tree.   vector<int> serialize(Node *root)    {       //Your code here       vector<int> v;       if(root==NULL)       {           v.push_back(-1);           return v;       }       serialize(root->left);       cout<<root->data<<" ";       serialize(root->right);   }      //Function to deserialize a list and construct the tree.   int i=0;   Node * deSerialize(vector<int> &A)   {      //Your code here      if(A.size()==0) return NULL;      if(A[i]==-1)       {          i++;          return NULL;      }      Node* root=new Node(A[i++]);      root->left=deSerialize(A);      root->right=deSerialize(A);      return root;   }
}; 
0
palakparihar1443 months ago
class Tree {   //Function to serialize a tree and return a list containing nodes of tree.public void serialize(Node root, ArrayList<Integer> A) {    //code     if(root == null){        return;    }        serialize(root.left, A);    A.add(root.data);    serialize(root.right, A);}//Function to deserialize a list and construct the tree.class Index {    int index;}public Node solve(ArrayList<Integer> A, int low, int high, Index index){    if(index.index >= A.size() || low > high){        Node root ;        return root = null;    }    //storing value of root    Node root = new Node(A.get(index.index));    index.index+=1;    // check if there exist any subtree further    if(low == high){        return root;    }    // find the next greater element to the right of root    int i;    for(i=low; i>=high; i++){        if(A.get(i) > root.data){            //found the start of right sub tree            break;        }    }    //constructing the left subtree    root.left = solve(A, index.index, i-1, index);    root.right = solve(A,i,high, index);    return root;}   public Node deSerialize(ArrayList<Integer> A)   {       //code here       // System.out.println(A);       Index index = new Index();       index.index = 0;       return solve(A, 0, A.size()-1,index);   }};
-1
mulayam6614 months ago
class Solution
{
    public:
    void helper2(Node *root,vector<int>&a) 
    {
        if(root==NULL)
        {
            a.push_back(int(NULL));
            return;
        }
        a.push_back(root->data);
        helper2(root->left,a);
        helper2(root->right,a);
        return ;
        
    }
    //Function to serialize a tree and return a list containing nodes of tree.
    vector<int> serialize(Node *root) 
    {
        vector<int>a;
        helper2(root,a);
        return a;
    }
    
    //Function to deserialize a list and construct the tree.
    int idx=0;
    Node * deSerialize(vector<int> &a)
    {
        if((a.size()-1)<idx||a[idx]==NULL)
       {
           idx++;
           return NULL;
       }
       Node*root=new Node(a[idx++]);
       root->left=deSerialize(a);
       root->right=deSerialize(a);
       return root;
    }

};

We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.