Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Serialize and Deserialize an N-ary Tree
Next article icon

Serialize and Deserialize a Binary Tree

Last Updated : 06 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Serialization is performed to store a tree in an array so that it can be later restored and deserialization is reading the tree back from the array.

Given a binary tree, the task is to complete the functions:

  • serialize(): stores the tree into an array arr[] and returns the array.
  • deSerialize(): deserializes the array to the tree and returns the root of the tree.

Note: Multiple nodes can have the same data and the node values are always positive.

Example:

Input:

Print-Nodes-in-Top-View-of-Binary-Tree-1

Output: [2, 1, 3]

Input:

Serialize-and-Deserialize-a-Binary-Tree-example

Output: [20, 10, 40, 30, 60]

Table of Content

  • How to store a general Binary Tree?
  • Using Level Order Traversal
  • How to serialize N-ary tree?

If the given Tree is a Binary Search Tree?

If the given Binary Tree is Binary Search Tree, we can store it by either storing preorder or postorder traversal. In the case of Binary Search Trees, only preorder or postorder traversal is sufficient to store structure information.

If given Binary Tree is Complete Tree?

A Binary Tree is complete if all levels are completely filled except possibly the last level and all nodes of last level are as left as possible (Binary Heaps are complete Binary Tree). For a complete Binary Tree, level order traversal is sufficient to store the tree. We know that the first node is root, next two nodes are nodes of next level, next four nodes are nodes of 2nd level and so on.

If given Binary Tree is Full Tree?

A full Binary is a Binary Tree where every node has either 0 or 2 children. It is easy to serialize such trees as every internal node has 2 children. We can simply store preorder traversal and store a bit with every node to indicate whether the node is an internal node or a leaf node.

How to serialise a general Binary Tree?

The idea to traverse the tree in preorder manner. At each node, append its value into the resultant list. If its left child exists, then recursively traverse the left subtree. Otherwise, append -1 to the resultant list. Similarly for right subtree, if right child node exists, then recursively traverse the right subtree. Otherwise append -1 to the resultant list. For deserialization, Traverse the array in pre-order manner. If the current element is -1, then return NULL. Otherwise, create a new node with value equal to current element and recursively construct the left and right subtree.

C++
//Driver Code Starts{ // C++ program to serialize and  // deserialize a binary tree. #include <bits/stdc++.h> using namespace std;  class Node{ public:     int data;     Node* left, *right;     Node (int x) {         data = x;         left = nullptr;         right = nullptr;     } }; //Driver Code Ends }   // Function which traverse the tree in preorder  // manner and adds nodes into result. void serializePreOrder(Node* root, vector<int> &arr) {          // Push -1 if root is null.     if (root == nullptr) {         arr.push_back(-1);         return;     }          // Push the root into result.     arr.push_back(root->data);          // Recursively traverse the      // left and right subtree.     serializePreOrder(root->left, arr);     serializePreOrder(root->right, arr); }  // Main function to serialize a tree. vector<int> serialize(Node *root) {     vector<int> arr;     serializePreOrder(root, arr);     return arr; }  // Function which traverse the array in preorder  // manner and constructs the tree. Node* deserializePreOrder(int &i, vector<int> &arr) {          // -1 meres null.     if (arr[i] == -1){         i++;         return nullptr;     }          // Create the root node.     Node* root = new Node(arr[i]);     i++;          // Create the left and right subtree.     root->left = deserializePreOrder(i, arr);     root->right = deserializePreOrder(i, arr);          return root; }   Node * deSerialize(vector<int> &arr) {    int i = 0;    return deserializePreOrder(i, arr); }   //Driver Code Starts{ // Print tree as level order void printLevelOrder(Node *root) {     if (root == nullptr) {         cout << "N ";         return;     }      queue<Node *> qq;     qq.push(root);     int nonNull = 1;      while (!qq.empty() && nonNull > 0) {         Node *curr = qq.front();         qq.pop();          if (curr == nullptr) {             cout << "N ";             continue;         }         nonNull--;          cout << (curr->data) << " ";         qq.push(curr->left);         qq.push(curr->right);         if (curr->left)             nonNull++;         if (curr->right)             nonNull++;     } }  int main() {      // Create a hard coded tree     //       10     //     /    \     //    20    30     //  /   \     // 40  60     Node* root = new Node(10);             root->left = new Node(20);             root->right = new Node(30);            root->left->left = new Node(40);     root->left->right = new Node(60);           vector<int> arr = serialize(root);     Node* res = deSerialize(arr);          printLevelOrder(res); } //Driver Code Ends } 
Java
//Driver Code Starts{ // Java program to serialize and  // deserialize a binary tree. import java.util.ArrayList; import java.util.Queue; import java.util.LinkedList;  class Node {     int data;     Node left, right;     Node (int x) {         data = x;         left = null;         right = null;     } }  class GfG { //Driver Code Ends }           // Function which traverse the tree in preorder      // manner and adds nodes into result.     static void serializePreOrder(Node root, ArrayList<Integer> arr) {                  // Push -1 if root is null.         if (root == null) {             arr.add(-1);             return;         }                  // Push the root into result.         arr.add(root.data);                  // Recursively traverse the          // left and right subtree.         serializePreOrder(root.left, arr);         serializePreOrder(root.right, arr);     }      // Main function to serialize a tree.     static ArrayList<Integer> serialize(Node root) {         ArrayList<Integer> arr = new ArrayList<>();         serializePreOrder(root, arr);         return arr;     }      // Function which traverse the array in preorder      // manner and constructs the tree.     static Node deserializePreOrder(int[] i, ArrayList<Integer> arr) {                  // -1 meres null.         if (arr.get(i[0]) == -1) {             i[0]++;             return null;         }                  // Create the root node.         Node root = new Node(arr.get(i[0]));         i[0]++;                  // Create the left and right subtree.         root.left = deserializePreOrder(i, arr);         root.right = deserializePreOrder(i, arr);                  return root;     }      // Main function to deserialize a tree.     static Node deSerialize(ArrayList<Integer> arr) {        int[] i = {0};        return deserializePreOrder(i, arr);     }   //Driver Code Starts{     // Print tree as level order     static void printLevelOrder(Node root) {         if (root == null) {             System.out.print("N ");             return;         }          Queue<Node> queue = new LinkedList<>();         queue.add(root);         int nonNull = 1;          while (!queue.isEmpty() && nonNull > 0) {             Node curr = queue.poll();              if (curr == null) {                 System.out.print("N ");                 continue;             }             nonNull--;              System.out.print(curr.data + " ");             queue.add(curr.left);             queue.add(curr.right);             if (curr.left != null)                 nonNull++;             if (curr.right != null)                 nonNull++;         }     }      public static void main(String[] args) {          // Create a hard coded tree         //       10         //     /    \         //    20    30         //  /   \         // 40  60         Node root = new Node(10);                 root.left = new Node(20);                 root.right = new Node(30);                root.left.left = new Node(40);         root.left.right = new Node(60);                   ArrayList<Integer> arr = serialize(root);         Node res = deSerialize(arr);                  printLevelOrder(res);     } }  //Driver Code Ends } 
Python
#Driver Code Starts{ # Python program to serialize and  # deserialize a binary tree.  from collections import deque  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None #Driver Code Ends }   # Function which traverse the tree in preorder  # manner and adds nodes into result. def serializePreOrder(root, arr):          # Push -1 if root is null.     if root is None:         arr.append(-1)         return          # Push the root into result.     arr.append(root.data)          # Recursively traverse the      # left and right subtree.     serializePreOrder(root.left, arr)     serializePreOrder(root.right, arr)  # Main function to serialize a tree. def serialize(root):     arr = []     serializePreOrder(root, arr)     return arr  # Function which traverse the array in preorder  # manner and constructs the tree. def deserializePreOrder(i, arr):          # -1 meres null.     if arr[i[0]] == -1:         i[0] += 1         return None          # Create the root node.     root = Node(arr[i[0]])     i[0] += 1          # Create the left and right subtree.     root.left = deserializePreOrder(i, arr)     root.right = deserializePreOrder(i, arr)          return root  # Main function to deserialize a tree. def deSerialize(arr):     i = [0]     return deserializePreOrder(i, arr)   #Driver Code Starts{ # Print tree as level order def printLevelOrder(root):     if root is None:         print("N ", end="")         return      queue = deque([root])     non_null = 1      while queue and non_null > 0:         curr = queue.popleft()          if curr is None:             print("N ", end="")             continue         non_null -= 1          print(curr.data, end=" ")         queue.append(curr.left)         queue.append(curr.right)         if curr.left:             non_null += 1         if curr.right:             non_null += 1  if __name__ == "__main__":      # Create a hard coded tree     #       10     #     /    \     #    20    30     #  /   \     # 40  60     root = Node(10)             root.left = Node(20)             root.right = Node(30)            root.left.left = Node(40)     root.left.right = Node(60)           arr = serialize(root)     res = deSerialize(arr)          printLevelOrder(res)  #Driver Code Ends } 
C#
//Driver Code Starts{ // C# program to serialize and  // deserialize a binary tree. using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;     public Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG { //Driver Code Ends }       // Function which traverse the tree in preorder      // manner and adds nodes into result.     static void serializePreOrder(Node root, List<int> arr) {                  // Push -1 if root is null.         if (root == null) {             arr.Add(-1);             return;         }                  // Push the root into result.         arr.Add(root.data);                  // Recursively traverse the          // left and right subtree.         serializePreOrder(root.left, arr);         serializePreOrder(root.right, arr);     }      // Main function to serialize a tree.     static List<int> serialize(Node root) {         List<int> arr = new List<int>();         serializePreOrder(root, arr);         return arr;     }      // Function which traverse the array in preorder      // manner and constructs the tree.     static Node deserializePreOrder(ref int i, List<int> arr) {                  // -1 meres null.         if (arr[i] == -1) {             i++;             return null;         }                  // Create the root node.         Node root = new Node(arr[i]);         i++;                  // Create the left and right subtree.         root.left = deserializePreOrder(ref i, arr);         root.right = deserializePreOrder(ref i, arr);                  return root;     }      // Main function to deserialize a tree.     static Node deSerialize(List<int> arr) {         int i = 0;         return deserializePreOrder(ref i, arr);     }   //Driver Code Starts{     // Print tree as level order     static void printLevelOrder(Node root) {         if (root == null) {             Console.Write("N ");             return;         }          Queue<Node> queue = new Queue<Node>();         queue.Enqueue(root);         int nonNull = 1;          while (queue.Count > 0 && nonNull > 0) {             Node curr = queue.Dequeue();              if (curr == null) {                 Console.Write("N ");                 continue;             }             nonNull--;              Console.Write(curr.data + " ");             queue.Enqueue(curr.left);             queue.Enqueue(curr.right);             if (curr.left != null)                 nonNull++;             if (curr.right != null)                 nonNull++;         }     }      static void Main() {          // Create a hard coded tree         //       10         //     /    \         //    20    30         //  /   \         // 40  60         Node root = new Node(10);         root.left = new Node(20);         root.right = new Node(30);         root.left.left = new Node(40);         root.left.right = new Node(60);          List<int> arr = serialize(root);         Node res = deSerialize(arr);          printLevelOrder(res);     } }  //Driver Code Ends } 
JavaScript
//Driver Code Starts{ // JavaScript program to serialize and  // deserialize a binary tree.  class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } } //Driver Code Ends }   // Function which traverse the tree in preorder  // manner and adds nodes into result. function serializePreOrder(root, arr) {          // Push -1 if root is null.     if (root === null) {         arr.push(-1);         return;     }          // Push the root into result.     arr.push(root.data);          // Recursively traverse the      // left and right subtree.     serializePreOrder(root.left, arr);     serializePreOrder(root.right, arr); }  // Main function to serialize a tree. function serialize(root) {     const arr = [];     serializePreOrder(root, arr);     return arr; }  // Function which traverse the array in preorder  // manner and constructs the tree. function deserializePreOrder(i, arr) {          // -1 meres null.     if (arr[i[0]] === -1) {         i[0]++;         return null;     }          // Create the root node.     const root = new Node(arr[i[0]]);     i[0]++;          // Create the left and right subtree.     root.left = deserializePreOrder(i, arr);     root.right = deserializePreOrder(i, arr);          return root; }  // Main function to deserialize a tree. function deserialize(arr) {     const i = [0];     return deserializePreOrder(i, arr); }   //Driver Code Starts{ // Print tree as level order function printLevelOrder(root) {     if (root === null) {         process.stdout.write("N ");         return;     }      const queue = [];     queue.push(root);     let nonNull = 1;      while (queue.length > 0 && nonNull > 0) {         const curr = queue.shift();          if (curr === null) {             process.stdout.write("N ");             continue;         }         nonNull--;          process.stdout.write(curr.data + " ");         queue.push(curr.left);         queue.push(curr.right);         if (curr.left) nonNull++;         if (curr.right) nonNull++;     } }  // Driver Code // Create a hard coded tree //       10 //     /    \ //    20    30 //  /   \ // 40  60 const root = new Node(10); root.left = new Node(20); root.right = new Node(30); root.left.left = new Node(40); root.left.right = new Node(60);  const arr = serialize(root); const res = deserialize(arr);  printLevelOrder(res);  //Driver Code Ends } 

Output
10 20 30 40 60 

Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(n)

Using Level Order Traversal

The idea is to traverse the tree in level order manner. Push the root node into a queue. While queue is not empty: For each node, if it is not null, then append its value into the resultant list and push its left and right child nodes into the queue. If current node is null, then push -1 into the resultant list.
For deserialization, create the root node with value equal to first element in the array and push this node into a queue. Traverse the array from index 1. Pop the front node from queue. If the current element is -1, then its left child node is null. Otherwise create a new node and link the nodes. Push the left node into the queue. Do the same for right subtree.

C++
//Driver Code Starts{ // C++ program to serialize and  // deserialize a binary tree. #include <iostream> #include <vector> #include <queue> using namespace std;  class Node{ public:     int data;     Node* left, *right;     Node (int x) {         data = x;         left = nullptr;         right = nullptr;     } }; //Driver Code Ends }   // Main function to serialize a tree. vector<int> serialize(Node *root) {     vector<int> arr;          queue<Node*> q;     q.push(root);          while (!q.empty()) {         Node* curr = q.front();         q.pop();                  // If curr node is null,         // append -1 to result.         if (curr == nullptr) {             arr.push_back(-1);             continue;         }                  // else push its value into         // result and push left and right         // child nodes into queue.         arr.push_back(curr->data);                  q.push(curr->left);         q.push(curr->right);     }          return arr; }   // Main function to deserialize a tree. Node * deSerialize(vector<int> &arr) {        // base case    if (arr[0]==-1) return nullptr;        // create root node and push     // it into queue    Node* root = new Node(arr[0]);    queue<Node*> q;    q.push(root);        int i = 1;    while (!q.empty()) {        Node* curr = q.front();        q.pop();                // If left node is not null        if (arr[i]!=-1) {            Node* left = new Node(arr[i]);            curr->left = left;            q.push(left);        }        i++;                // If right node is not null        if (arr[i]!=-1) {            Node* right = new Node(arr[i]);            curr->right = right;            q.push(right);        }        i++;    }        return root; }   //Driver Code Starts{ // Print tree as level order void printLevelOrder(Node *root) {     if (root == nullptr) {         cout << "N ";         return;     }      queue<Node *> qq;     qq.push(root);     int nonNull = 1;      while (!qq.empty() && nonNull > 0) {         Node *curr = qq.front();         qq.pop();          if (curr == nullptr) {             cout << "N ";             continue;         }         nonNull--;          cout << (curr->data) << " ";         qq.push(curr->left);         qq.push(curr->right);         if (curr->left)             nonNull++;         if (curr->right)             nonNull++;     } }  int main() {      // Create a hard coded tree     //       10     //     /    \     //    20    30     //  /   \     // 40  60     Node* root = new Node(10);             root->left = new Node(20);             root->right = new Node(30);            root->left->left = new Node(40);     root->left->right = new Node(60);           vector<int> arr = serialize(root);     Node* res = deSerialize(arr);          printLevelOrder(res); }  //Driver Code Ends } 
Java
//Driver Code Starts{ // Java program to serialize and  // deserialize a binary tree. import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue;  class Node {     int data;     Node left, right;     Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG { //Driver Code Ends }           // Main function to serialize a tree.     static ArrayList<Integer> serialize(Node root) {         ArrayList<Integer> arr = new ArrayList<>();         Queue<Node> q = new LinkedList<>();         q.add(root);          while (!q.isEmpty()) {             Node curr = q.poll();              // If curr node is null,             // append -1 to result.             if (curr == null) {                 arr.add(-1);                 continue;             }              // else push its value into             // result and push left and right             // child nodes into queue.             arr.add(curr.data);             q.add(curr.left);             q.add(curr.right);         }          return arr;     }      // Main function to deserialize a tree.     static Node deSerialize(ArrayList<Integer> arr) {          // base case         if (arr.get(0) == -1) return null;          // create root node and push          // it into queue         Node root = new Node(arr.get(0));         Queue<Node> q = new LinkedList<>();         q.add(root);          int i = 1;         while (!q.isEmpty()) {             Node curr = q.poll();              // If left node is not null             if (arr.get(i) != -1) {                 Node left = new Node(arr.get(i));                 curr.left = left;                 q.add(left);             }             i++;              // If right node is not null             if (arr.get(i) != -1) {                 Node right = new Node(arr.get(i));                 curr.right = right;                 q.add(right);             }             i++;         }          return root;     }   //Driver Code Starts{     // Print tree as level order     static void printLevelOrder(Node root) {         if (root == null) {             System.out.print("N ");             return;         }          Queue<Node> queue = new LinkedList<>();         queue.add(root);         int nonNull = 1;          while (!queue.isEmpty() && nonNull > 0) {             Node curr = queue.poll();              if (curr == null) {                 System.out.print("N ");                 continue;             }             nonNull--;              System.out.print(curr.data + " ");             queue.add(curr.left);             queue.add(curr.right);             if (curr.left != null)                 nonNull++;             if (curr.right != null)                 nonNull++;         }     }      public static void main(String[] args) {          // Create a hard coded tree         //       10         //     /    \         //    20    30         //  /   \         // 40  60         Node root = new Node(10);         root.left = new Node(20);         root.right = new Node(30);         root.left.left = new Node(40);         root.left.right = new Node(60);          ArrayList<Integer> arr = serialize(root);         Node res = deSerialize(arr);          printLevelOrder(res);     } }  //Driver Code Ends } 
Python
#Driver Code Starts{ # Python program to serialize and  # deserialize a binary tree. from collections import deque  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None #Driver Code Ends }   # Main function to serialize a tree. def serialize(root):     arr = []     q = deque([root])          while q:         curr = q.popleft()          # If curr node is null,         # append -1 to result.         if not curr:             arr.append(-1)             continue                  # else push its value into         # result and push left and right         # child nodes into queue.         arr.append(curr.data)         q.append(curr.left)         q.append(curr.right)          return arr  # Main function to deserialize a tree. def deSerialize(arr):      # base case     if arr[0] == -1:         return None          # create root node and push      # it into queue     root = Node(arr[0])     q = deque([root])          i = 1     while q:         curr = q.popleft()          # If left node is not null         if arr[i] != -1:             left = Node(arr[i])             curr.left = left             q.append(left)         i += 1          # If right node is not null         if arr[i] != -1:             right = Node(arr[i])             curr.right = right             q.append(right)         i += 1          return root   #Driver Code Starts{ # Print tree as level order def printLevelOrder(root):     if root is None:         print("N ", end="")         return      queue = deque([root])     non_null = 1      while queue and non_null > 0:         curr = queue.popleft()          if curr is None:             print("N ", end="")             continue         non_null -= 1          print(curr.data, end=" ")         queue.append(curr.left)         queue.append(curr.right)         if curr.left:             non_null += 1         if curr.right:             non_null += 1  if __name__ == "__main__":      # Create a hard coded tree     #       10     #     /    \     #    20    30     #  /   \     # 40  60     root = Node(10)     root.left = Node(20)     root.right = Node(30)     root.left.left = Node(40)     root.left.right = Node(60)          arr = serialize(root)     res = deSerialize(arr)      printLevelOrder(res)  #Driver Code Ends } 
C#
//Driver Code Starts{ // C# program to serialize and  // deserialize a binary tree. using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;     public Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG { //Driver Code Ends }           // Main function to serialize a tree.     static List<int> serialize(Node root) {         List<int> arr = new List<int>();                  Queue<Node> q = new Queue<Node>();         q.Enqueue(root);                  while (q.Count > 0) {             Node curr = q.Dequeue();                          // If curr node is null,             // append -1 to result.             if (curr == null) {                 arr.Add(-1);                 continue;             }                          // else push its value into             // result and push left and right             // child nodes into queue.             arr.Add(curr.data);                          q.Enqueue(curr.left);             q.Enqueue(curr.right);         }                  return arr;     }      // Main function to deserialize a tree.     static Node deSerialize(List<int> arr) {                  // base case         if (arr[0] == -1) return null;                  // create root node and push          // it into queue         Node root = new Node(arr[0]);         Queue<Node> q = new Queue<Node>();         q.Enqueue(root);                  int i = 1;         while (q.Count > 0) {             Node curr = q.Dequeue();                          // If left node is not null             if (arr[i] != -1) {                 Node left = new Node(arr[i]);                 curr.left = left;                 q.Enqueue(left);             }             i++;                          // If right node is not null             if (arr[i] != -1) {                 Node right = new Node(arr[i]);                 curr.right = right;                 q.Enqueue(right);             }             i++;         }                  return root;     }   //Driver Code Starts{     // Print tree as level order     static void printLevelOrder(Node root) {         if (root == null) {             Console.Write("N ");             return;         }          Queue<Node> queue = new Queue<Node>();         queue.Enqueue(root);         int nonNull = 1;          while (queue.Count > 0 && nonNull > 0) {             Node curr = queue.Dequeue();              if (curr == null) {                 Console.Write("N ");                 continue;             }             nonNull--;              Console.Write(curr.data + " ");             queue.Enqueue(curr.left);             queue.Enqueue(curr.right);             if (curr.left != null)                 nonNull++;             if (curr.right != null)                 nonNull++;         }     }      static void Main(string[] args) {          // Create a hard coded tree         //       10         //     /    \         //    20    30         //  /   \         // 40   60         Node root = new Node(10);                 root.left = new Node(20);                 root.right = new Node(30);                root.left.left = new Node(40);         root.left.right = new Node(60);                   List<int> arr = serialize(root);         Node res = deSerialize(arr);                  printLevelOrder(res);     } }  //Driver Code Ends } 
JavaScript
//Driver Code Starts{ // JavaScript program to serialize and  // deserialize a binary tree.  class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } } //Driver Code Ends }   // Main function to serialize a tree. function serialize(root) {     const arr = [];          const q = [root];          while (q.length > 0) {         const curr = q.shift();                  // If curr node is null,         // append -1 to result.         if (curr === null) {             arr.push(-1);             continue;         }                  // else push its value into         // result and push left and right         // child nodes into queue.         arr.push(curr.data);                  q.push(curr.left);         q.push(curr.right);     }          return arr; }  // Main function to deserialize a tree. function deserialize(arr) {          // base case     if (arr[0] === -1) return null;          // create root node and push      // it into queue     const root = new Node(arr[0]);     const q = [root];          let i = 1;     while (q.length > 0) {         const curr = q.shift();                  // If left node is not null         if (arr[i] !== -1) {             const left = new Node(arr[i]);             curr.left = left;             q.push(left);         }         i++;                  // If right node is not null         if (arr[i] !== -1) {             const right = new Node(arr[i]);             curr.right = right;             q.push(right);         }         i++;     }          return root; }   //Driver Code Starts{ // Print tree as level order function printLevelOrder(root) {     if (root === null) {         process.stdout.write("N ");         return;     }      const queue = [];     queue.push(root);     let nonNull = 1;      while (queue.length > 0 && nonNull > 0) {         const curr = queue.shift();          if (curr === null) {             process.stdout.write("N ");             continue;         }         nonNull--;          process.stdout.write(curr.data + " ");         queue.push(curr.left);         queue.push(curr.right);         if (curr.left) nonNull++;         if (curr.right) nonNull++;     } }  // Driver Code // Create a hard coded tree //       10 //     /    \ //    20    30 //  /   \ // 40  60 const root = new Node(10); root.left = new Node(20); root.right = new Node(30); root.left.left = new Node(40); root.left.right = new Node(60);  const arr = serialize(root); const res = deserialize(arr);  printLevelOrder(res);  //Driver Code Ends } 

Output
10 20 30 40 60 

Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(n)

How much extra space is required in above solution?

If there are n keys, then the above solution requires n+1 markers which may be better than simple solution (storing keys twice) in situations where keys are big or keys have big data items associated with them.

Can we optimize it further?

The above solution can be optimized in many ways. If we take a closer look at the above serialized trees, we can observe that all leaf nodes require two markers. One simple optimization is:

  • Store a separate bit with every node to indicate that the node is internal or external. 
  • This way we don’t have to store two markers with every leaf node as leaves can be identified by the extra bit. 
  • We still need a marker for internal nodes with one child. 

For example, in the following diagram, the character ‘ is used to indicate an internal node set bit, and ‘/’ is used as NULL marker.

Serialize-and-Deserialize-a-Binary-Tree-1

How to serialize N-ary tree?

In an N-ary tree, there is no designated left or right child. We can store an ‘end of children’ marker with every node. The following diagram shows serialization where ‘)’ is used as the end of the children marker.

Serialize-and-Deserialize-a-Binary-Tree-2


Please refer to Serialize and Deserialize an N-ary Tree for implementation.



Next Article
Serialize and Deserialize an N-ary Tree
author
kartik
Improve
Article Tags :
  • DSA
  • Tree
  • Accolite
  • Adobe
  • Amazon
  • Flipkart
  • InMobi
  • Linkedin
  • MAQ Software
  • Microsoft
  • Paytm
  • Quikr
  • Yahoo
Practice Tags :
  • Accolite
  • Adobe
  • Amazon
  • Flipkart
  • InMobi
  • Linkedin
  • MAQ Software
  • Microsoft
  • Paytm
  • Quikr
  • Yahoo
  • Tree

Similar Reads

  • Serialize and Deserialize an N-ary Tree
    Given an N-ary tree where every node has the most N children. How to serialize and deserialize it? Serialization is to store a tree in a file so that it can be later restored. The structure of the tree must be maintained. Deserialization is reading the tree back from the file. This post is mainly an
    11 min read
  • Compress a Binary Tree into an integer diagonally
    Given a Binary Tree consisting of N nodes, the task is to first compress the tree diagonally to get a list of integers and then, again compress the list to get a single integer using the following operations: When a tree is compressed diagonally, its value in binary representation gets compressed.Co
    10 min read
  • Binary Tree Traversal
    Binary trees are fundamental data structures in computer science and understanding their traversal is crucial for various applications. Traversing a binary tree means visiting all the nodes in a specific order. There are several traversal methods, each with its unique applications and benefits. This
    15+ min read
  • Difference between General tree and Binary tree
    General Tree: In the data structure, General tree is a tree in which each node can have either zero or many child nodes. It can not be empty. In general tree, there is no limitation on the degree of a node. The topmost node of a general tree is called the root node. There are many subtrees in a gene
    2 min read
  • Search a node in Binary Tree
    Given a Binary tree and a key. The task is to search and check if the given key exists in the binary tree or not. Examples: Input: Output: TrueInput: Output: False Approach:The idea is to use any of the tree traversals to traverse the tree and while traversing check if the current node matches with
    7 min read
  • Print all internal nodes of a Binary tree
    Given a Binary tree, the task is to print all the internal nodes in a tree. An internal node is a node which carries at least one child or in other words, an internal node is not a leaf node. Here we intend to print all such internal nodes in level order. Consider the following Binary Tree: Input: O
    7 min read
  • Deepest left leaf node in a binary tree | iterative approach
    Given a Binary Tree, find the deepest leaf node that is left child of its parent. For example, consider the following tree. The deepest left leaf node is the node with value 9. Examples: Input : 1 / \ 2 3 / / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 9 Recursive approach to this problem is discussed hereFor
    8 min read
  • Binary Tree (Array implementation)
    Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
    6 min read
  • Double Order Traversal of a Binary Tree
    Given a Binary Tree, the task is to find its Double Order Traversal. Double Order Traversal is a tree traversal technique in which every node is traversed twice in the following order: Visit the Node.Traverse the Left Subtree.Visit the Node.Traverse the Right Subtree.Examples: Input: Output: 1 7 4 4
    6 min read
  • Reverse alternate levels of a perfect binary tree
    Given a perfect binary tree, your task is to reverse the nodes present at alternate levels. Examples: Input: root = [1, 3, 2] 1 / \ 3 2Output: 1 / \ 2 3Explanation: Nodes at level 2 are reversed. Input: root = [1, 2, 3, 4, 5, 6, 7] 1 / \ 2 3 / \ / \ 4 5 6 7Output: 1 / \ 3 2 / \ / \ 4 5 6 7Explanatio
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences