{"id":5057,"date":"2023-06-23T17:48:28","date_gmt":"2023-06-23T12:18:28","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=5057"},"modified":"2023-06-23T17:49:11","modified_gmt":"2023-06-23T12:19:11","slug":"serialize-and-deserialize-a-binary-tree","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/serialize-and-deserialize-a-binary-tree\/","title":{"rendered":"Serialize and Deserialize a Binary Tree"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"text_open\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement<\/a><\/li><li><a href=\"#sample-test-cases\">Sample Test Cases<\/a><\/li><li><a href=\"#depth-first-search-traversal-based-approach\">Depth First Search Traversal-based Approach<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#c-code\">C++ Code<\/a><\/li><li><a href=\"#java-code\">Java Code<\/a><\/li><li><a href=\"#python-code\">Python Code<\/a><\/li><\/ul><li><a href=\"#faqs\">FAQs<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-what-traversal-algorithm-is-used-in-the-approach-for-the-above-problem\">Q.1: What traversal algorithm is used in the approach for the above problem?<\/a><\/li><li><a href=\"#q2-what-is-the-significance-of-the-marker-variable-in-the-above-problem\">Q.2: What is the significance of the marker variable in the above problem?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement<\/h2>\n\n\n\n<p>Given a binary tree, serialize and deserialize the binary tree.<\/p>\n\n\n\n<ul><li><strong>Serialize: <\/strong>Write the tree into a file.<\/li><li><strong>Deserialize:<\/strong> Read the tree from a file and reconstruct the binary tree into memory.<\/li><\/ul>\n\n\n\n<h2 id=\"sample-test-cases\">Sample Test Cases<\/h2>\n\n\n\n<p><strong>Input 1:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large is-resized\"><img  loading=\"lazy\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5109 pk-lazyload\"  width=\"613\"  height=\"560\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 613px) 100vw, 613px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image2-4-1024x937.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image2-4-1024x937.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image2-4-300x274.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image2-4-768x703.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image2-4-380x348.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image2-4-550x503.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image2-4-800x732.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image2-4-1160x1061.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image2-4.png 1292w\" ><\/figure><\/div>\n\n\n\n<p><strong>Output 1:<\/strong><br>[1,2,3,null,null,4,5]\n\n\n\n<p><strong>Input 2:<\/strong> []\n\n\n\n<p>Output 2:<br>[] \/\/ Empty tree<\/p>\n\n\n\n<h2 id=\"depth-first-search-traversal-based-approach\">Depth First Search Traversal-based Approach<\/h2>\n\n\n\n<p>We can solve this problem with a Depth First Search Traversal-based algorithm. The idea is to perform a DFS on the tree and serialize individual nodes to the output stream recursively. The traversal used here will be a pre-order traversal. To help in the process of deserializing the tree, we will use some marker variables to represent a null pointer.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"692\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5110 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-1024x692.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-1024x692.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-300x203.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-768x519.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-1536x1039.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-2048x1385.png 2048w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-380x257.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-550x372.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-800x541.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6-1160x784.png 1160w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image1-6.png 2575w\" ><\/figure>\n\n\n\n<p>Consider the above image, in this binary tree, the marker Mi represents the null nodes which make the process of deserializing the binary tree easier. The numbering of the markers merely represents the relative positioning of the marker with respect to each other.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img  loading=\"lazy\"  width=\"1024\"  height=\"95\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-5111 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-1024x95.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-1024x95.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-300x28.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-768x71.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-1536x143.png 1536w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-2048x191.png 2048w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-380x35.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-550x51.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-800x74.png 800w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/12\/image3-2-1160x108.png 1160w\" ><\/figure>\n\n\n\n<p>The serialized tree, of the above binary tree, would look like this image.<br>During deserializing the tree, we will make a new node for every node which is not a marker node, while doing a pre-order traversal on the tree.<\/p>\n\n\n\n<h3 id=\"c-code\">C++ Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">const int MARKER = INT_MIN\nvoid serialize(TreeNode * node, ostream &amp; sstream) {\n  if (node == nullptr) {\n    sstream.write((char * ) &amp; MARKER, sizeof(MARKER));\n    return;\n  }\n  sstream.write((char * ) &amp; node -> data, sizeof(node -> data));\n  serialize(node -> left, sstream);\n  serialize(node -> right, sstream);\n}\n\nTreeNode * deserialize(istream &amp; sstream) {\n  if (sstream.eof() == true) {\n    return nullptr;\n  }\n  int value;\n  sstream.read((char * ) &amp; value, sizeof(value));\n  if (value == MARKER) {\n    return nullptr;\n  }\n\n  TreeNode * newNode = new TreeNode(value);\n  newNode -> left = deserialize(sstream);\n  newNode -> right = deserialize(sstream);\n\n  return newNode;\n}<\/pre>\n\n\n\n<h3 id=\"java-code\">Java Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">static final int MARKER = Integer.MIN_VALUE;\n\n  public static void serialize(TreeNode node, ObjectOutputStream stream) throws java.io.IOException {\n    if (node == null) {\n      stream.writeInt(MARKER);\n      return;\n    }\n\n    stream.writeInt(node.data);\n    serialize(node.left, stream);\n    serialize(node.right, stream);\n  }\n\n  public static TreeNode deserialize(ObjectInputStream stream) throws java.io.IOException {\n    int value = stream.readInt();\n    if (value == MARKER) {\n      return null;\n    }\n\n    TreeNode node = new TreeNode(val);\n    node.left = deserialize(stream);\n    node.right = deserialize(stream);\n    return node;\n  }<\/pre>\n\n\n\n<h3 id=\"python-code\">Python Code<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">MARKER = 99999999999\ndef serialize(node, stream):\n  if node == None:\n    stream.dump(MARKER);\n    return\n  stream.dump(node.data);\n  serialize(node.left, stream)\n  serialize(node.right, stream)\n\ndef deserialize(stream):\n    try:\n      value = pickle.load(stream)\n      if value == MARKER:\n          return None\n      else:\n          node = BinaryTreeNode(data);\n          node.left = deserialize(stream)\n          node.right = deserialize(stream)\n          return node\n    except pickle.UnpicklingError:\n      return None<\/pre>\n\n\n\n<p id=\"complexity-analysis\"><strong>Complexity Analysis<\/strong><\/p>\n\n\n\n<p><strong>Time Complexity:<\/strong> O(n)<br><strong>Space Complexity:<\/strong> O(logn)<\/p>\n\n\n\n<h2 id=\"faqs\">FAQs<\/h2>\n\n\n\n<h3 id=\"q1-what-traversal-algorithm-is-used-in-the-approach-for-the-above-problem\"><span id=\"q-1-what-traversal-algorithm-is-used-in-the-approach-for-the-above-problem\">Q.1: What traversal algorithm is used in the approach for the above problem?<\/span><\/h3>\n\n\n\n<p><strong>Ans<\/strong>. A Depth-First Search(DFS) is used to solve the above problem.<\/p>\n\n\n\n<h3 id=\"q2-what-is-the-significance-of-the-marker-variable-in-the-above-problem\"><span id=\"q-2-what-is-the-significance-of-the-marker-variable-in-the-above-problem\">Q.2: What is the significance of the marker variable in the above problem?<\/span><\/h3>\n\n\n\n<p><strong>Ans.<\/strong> The marker variable is used to signify the null nodes of the tree, which helps in de-serializing the binary tree.<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given a binary tree, serialize and deserialize the binary tree. Serialize: Write the tree into a&hellip;\n","protected":false},"author":5,"featured_media":5112,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"1","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[395,689],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/5057"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=5057"}],"version-history":[{"count":6,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/5057\/revisions"}],"predecessor-version":[{"id":20694,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/5057\/revisions\/20694"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/5112"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=5057"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=5057"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=5057"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}