jayati

Serialize and Deserialize a Binary Tree

Oct 20th, 2023
1,096
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.77 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. // Tree Node
  7. struct Node {
  8.     int data;
  9.     Node *left;
  10.     Node *right;
  11.  
  12.     Node(int val) {
  13.         data = val;
  14.         left = right = NULL;
  15.     }
  16. };
  17.  
  18. // Function to Build Tree
  19. Node *buildTree(string str) {
  20.     // Corner Case
  21.     if (str.length() == 0 || str[0] == 'N')
  22.         return NULL;
  23.  
  24.     // Creating vector of strings from input
  25.     // string after spliting by space
  26.     vector<string> ip;
  27.  
  28.     istringstream iss(str);
  29.     for (string str; iss >> str;)
  30.         ip.push_back(str);
  31.  
  32.     // Create the root of the tree
  33.     Node *root = new Node(stoi(ip[0]));
  34.  
  35.     // Push the root to the queue
  36.     queue<Node *> queue;
  37.     queue.push(root);
  38.  
  39.     // Starting from the second element
  40.     int i = 1;
  41.     while (!queue.empty() && i < ip.size()) {
  42.  
  43.         // Get and remove the front of the queue
  44.         Node *currNode = queue.front();
  45.         queue.pop();
  46.  
  47.         // Get the current Node's value from the string
  48.         string currVal = ip[i];
  49.  
  50.         // If the left child is not null
  51.         if (currVal != "N") {
  52.  
  53.             // Create the left child for the current Node
  54.             currNode->left = new Node(stoi(currVal));
  55.  
  56.             // Push it to the queue
  57.             queue.push(currNode->left);
  58.         }
  59.  
  60.         // For the right child
  61.         i++;
  62.         if (i >= ip.size())
  63.             break;
  64.         currVal = ip[i];
  65.  
  66.         // If the right child is not null
  67.         if (currVal != "N") {
  68.  
  69.             // Create the right child for the current Node
  70.             currNode->right = new Node(stoi(currVal));
  71.  
  72.             // Push it to the queue
  73.             queue.push(currNode->right);
  74.         }
  75.         i++;
  76.     }
  77.  
  78.     return root;
  79. }
  80.  
  81.  
  82. // } Driver Code Ends
  83. /* A binary tree node has data, pointer to left child
  84.    and a pointer to right child  
  85. struct Node
  86. {
  87.     int data;
  88.     Node* left;
  89.     Node* right;
  90. }; */
  91.  
  92.  
  93. class Solution
  94. {
  95.     public:
  96.  
  97.    
  98.     vector<int> serialize(Node *root)
  99.     {
  100.         //Your code here
  101.         vector<int> ans;
  102.         if(root==NULL)
  103.         {
  104.             return ans;
  105.         }
  106.          queue<Node*> q;
  107.          q.push(root);
  108.          while(!q.empty())
  109.          {
  110.              Node* node = q.front();
  111.              q.pop();
  112.              if(node==NULL)
  113.              {
  114.                  ans.push_back(-1);
  115.              }
  116.              else
  117.              {
  118.                  ans.push_back(node->data);
  119.              }
  120.              if(node!=NULL)
  121.              {
  122.                  q.push(node->left);
  123.                  q.push(node->right);
  124.              }
  125.          }
  126.         return ans;
  127.     }
  128.    
  129.     //Function to deserialize a list and construct the tree.
  130.     Node * deSerialize(vector<int> &A)
  131.     {
  132.       int index = 0;
  133.       if(A.size()==index)
  134.       {
  135.           return NULL;
  136.       }
  137.       int val = A[index++];
  138.       if(val==-1)
  139.       {
  140.           return NULL;
  141.       }
  142.       Node* root = new Node(val);
  143.       queue<Node*> q;
  144.       q.push(root);
  145.       while(!q.empty())
  146.       {
  147.            Node* node = q.front();
  148.            q.pop();
  149.            val = A[index++];
  150.            if(val==-1)
  151.            {
  152.                node->left=NULL;
  153.            }
  154.            else
  155.            {
  156.                Node* temp1 = new Node(val);
  157.                node->left= temp1;
  158.                q.push(temp1);
  159.            }
  160.            val = A[index++];
  161.            if(val==-1)
  162.            {
  163.                node->right = NULL;
  164.            }
  165.            else
  166.            {
  167.                 Node* temp2 = new Node(val);
  168.                node->right= temp2;
  169.                q.push(temp2);
  170.            }
  171.       }
  172.       return root;
  173.        
  174.     }
  175.  
  176. };
  177.  
  178. //{ Driver Code Starts.
  179.  
  180. void inorder(Node *root) {
  181.     if (root == NULL)
  182.         return;
  183.     inorder(root->left);
  184.     cout << root->data << " ";
  185.     inorder(root->right);
  186. }
  187.  
  188. void _deleteTree(Node* node)  
  189. {  
  190.     if (node == NULL) return;  
  191.  
  192.     /* first delete both subtrees */
  193.     _deleteTree(node->left);  
  194.     _deleteTree(node->right);  
  195.  
  196.     /* then delete the node */
  197.     //cout << "Deleting node: " << node->data << endl;  
  198.     delete node;  
  199. }  
  200.  
  201. /* Deletes a tree and sets the root as NULL */
  202. void deleteTree(Node** node_ref)  
  203. {  
  204.     _deleteTree(*node_ref);  
  205.     *node_ref = NULL;  
  206. }  
  207.  
  208. int main() {
  209.     int tc;
  210.     scanf("%d ", &tc);
  211.     while (tc--) {
  212.         string treeString;
  213.         getline(cin, treeString);
  214.         Node *root = buildTree(treeString);
  215.        
  216.         Solution serial, deserial;
  217.         vector<int> A = serial.serialize(root);
  218.         deleteTree(&root);
  219.         Node *getRoot = deserial.deSerialize(A);
  220.         inorder(getRoot);
  221.         cout << "\n";
  222.  
  223.     }
  224.  
  225.  
  226.     return 0;
  227. }
  228. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment