<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>serialization Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/serialization/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/serialization/</link>
	<description></description>
	<lastBuildDate>Sat, 10 Aug 2019 08:01:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>serialization Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/serialization/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 331. Verify Preorder Serialization of a Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-331-verify-preorder-serialization-of-a-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-331-verify-preorder-serialization-of-a-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 13 Apr 2018 15:26:50 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[tree]]></category>
		<category><![CDATA[varify]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2480</guid>

					<description><![CDATA[<p>Problem 题目大意：验证二叉树前序遍历的序列化是否合法。 https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/description/ One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node&#8217;s&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-331-verify-preorder-serialization-of-a-binary-tree/">花花酱 LeetCode 331. Verify Preorder Serialization of a Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>题目大意：验证二叉树前序遍历的序列化是否合法。</p>
<p><a href="https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/description/">https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/description/</a></p>
<p>One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node&#8217;s value. If it is a null node, we record using a sentinel value such as <code>#</code>.</p>
<pre class="crayon:false">     _9_
    /   \
   3     2
  / \   / \
 4   1  #  6
/ \ / \   / \
# # # #   # #
</pre>
<p>For example, the above binary tree can be serialized to the string <code>"9,3,4,#,#,1,#,#,2,#,6,#,#"</code>, where <code>#</code>represents a null node.</p>
<p>Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.</p>
<p>Each comma separated value in the string must be either an integer or a character <code>'#'</code> representing <code>null</code>pointer.</p>
<p>You may assume that the input format is always valid, for example it could never contain two consecutive commas such as <code>"1,,3"</code>.</p>
<p><strong>Example 1:</strong><br />
<code>"9,3,4,#,#,1,#,#,2,#,6,#,#"</code><br />
Return <code>true</code></p>
<p><strong>Example 2:</strong><br />
<code>"1,#"</code><br />
Return <code>false</code></p>
<p><strong>Example 3:</strong><br />
<code>"9,#,#,1"</code><br />
Return <code>false</code></p>
<p><b>Credits:</b><br />
Special thanks to <a href="https://leetcode.com/discuss/user/dietpepsi">@dietpepsi</a> for adding this problem and creating all test cases.</p>
<h1><strong>Solution: Recursion</strong></h1>
<ol>
<li>If a node is not null, it must has two children, thus verify left subtree and right subtree recursively.</li>
<li>If a not is null, the current char must be &#8216;#&#8217;</li>
</ol>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(h)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 5 ms
class Solution {
public:
  bool isValidSerialization(string preorder) {
    int pos = 0;    
    return isValid(preorder, pos) &amp;&amp; pos == preorder.length();
  }
private:
  bool isValid(const string&amp; s, int&amp; pos) {    
    if (pos &gt;= s.length()) return false;
    if (isdigit(s[pos])) {      
      while (isdigit(s[pos])) ++pos;
      return isValid(s, ++pos) &amp;&amp; isValid(s, ++pos);
    }
    return s[pos++] == '#';
  }
};</pre><p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-331-verify-preorder-serialization-of-a-binary-tree/">花花酱 LeetCode 331. Verify Preorder Serialization of a Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-331-verify-preorder-serialization-of-a-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 652. Find Duplicate Subtrees</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-652-find-duplicate-subtrees/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-652-find-duplicate-subtrees/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 31 Dec 2017 23:18:34 +0000</pubDate>
				<category><![CDATA[Medium]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[hash]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[subtree]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1390</guid>

					<description><![CDATA[<p>652.&#160;Find Duplicate SubtreesMedium730151FavoriteShare Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-652-find-duplicate-subtrees/">花花酱 LeetCode 652. Find Duplicate Subtrees</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[


<p>

652.&nbsp;Find Duplicate SubtreesMedium730151FavoriteShare</p>



<p>Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any&nbsp;<strong>one</strong>&nbsp;of them.</p>



<p>Two trees are duplicate if they have the same structure with same node values.</p>



<p><strong>Example 1:</strong></p>



<p>The following are two duplicate subtrees:</p>



<pre class="wp-block-preformatted; crayon:false">        1
       / \
      2   3
     /   / \
    4   2   4
       /
      4</pre>



<p>  2<br> /<br>4</p>



<p>and</p>



<p>4</p>



<p>Therefore, you need to return above trees&#8217; root in the form of a list.

</p>



<figure class="wp-block-image"><img src="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/652-ep146-1.png" alt=""/></figure>



<h2><strong>Solution 1: Serialization </strong></h2>



<p>Time complexity: O(n^2)<br>Space complexity: O(n^2) </p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 29 ms
class Solution {
public:
    vector&lt;TreeNode*&gt; findDuplicateSubtrees(TreeNode* root) {
        unordered_map&lt;string, int&gt; counts;
        vector&lt;TreeNode*&gt; ans;
        serialize(root, counts, ans);
        return ans;
    }
private:
    string serialize(TreeNode* root, unordered_map&lt;string, int&gt;&amp; counts, vector&lt;TreeNode*&gt;&amp; ans) {
        if (!root) return &quot;#&quot;;
        string key = to_string(root-&gt;val) + &quot;,&quot; 
                     + serialize(root-&gt;left, counts, ans) + &quot;,&quot; 
                     + serialize(root-&gt;right, counts, ans);
        if (++counts[key] == 2)
            ans.push_back(root);
        return key;
    }
};</pre>
</div></div>



<p><strong>Solution 2: int id for each unique subtree</strong></p>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 8 ms
class Solution {
public:
  vector&lt;TreeNode*&gt; findDuplicateSubtrees(TreeNode* root) {
    unordered_map&lt;long, pair&lt;int,int&gt;&gt; counts;    
    vector&lt;TreeNode*&gt; ans;
    getId(root, counts, ans);
    return ans;
  }
private:
  int getId(TreeNode* root, 
            unordered_map&lt;long, pair&lt;int,int&gt;&gt;&amp; counts,
            vector&lt;TreeNode*&gt;&amp; ans) {
    if (!root) return 0;
    long key = (static_cast&lt;long&gt;(static_cast&lt;unsigned&gt;(root-&gt;val)) &lt;&lt; 32) +
               (getId(root-&gt;left, counts, ans) &lt;&lt; 16) +
                getId(root-&gt;right, counts, ans);    
    auto&amp; p = counts[key];
    if (p.second++ == 0)
      p.first = counts.size();    
    else if (p.second == 2)
      ans.push_back(root);
    return p.first;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-652-find-duplicate-subtrees/">花花酱 LeetCode 652. Find Duplicate Subtrees</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-652-find-duplicate-subtrees/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 449. Serialize and Deserialize BST</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-449-serialize-and-deserialize-bst/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-449-serialize-and-deserialize-bst/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 19 Oct 2017 07:02:58 +0000</pubDate>
				<category><![CDATA[Medium]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary fortmat]]></category>
		<category><![CDATA[deserializtion]]></category>
		<category><![CDATA[serialization]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=629</guid>

					<description><![CDATA[<p>Problem: Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-449-serialize-and-deserialize-bst/">花花酱 LeetCode 449. Serialize and Deserialize BST</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/GDqVCQcmxgU?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p>
<p>Design an algorithm to serialize and deserialize a <b>binary search tree</b>. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.</p>
<p><b>The encoded string should be as compact as possible.</b></p>
<p><b>Note:</b> Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.</p>
<p><strong>Idea:</strong></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/449-ep91.png"><img class="alignnone size-full wp-image-640" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/449-ep91.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/449-ep91.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/449-ep91-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/449-ep91-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/449-ep91-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>Binary format</p>
<p>serialized size: 4*n bytes, n is the number of nodes in the BST.</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p><strong>Solution:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 19 ~ 26 ms (&lt;93.31%)
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string s;
        serialize(root, s);
        return s;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {        
        int pos = 0;
        return deserialize(data, pos, INT_MIN, INT_MAX);
    }
private:
    void serialize(TreeNode* root, string&amp; s) {
        if (!root) return;    
        s.append(reinterpret_cast&lt;const char*&gt;(&amp;root-&gt;val), sizeof(root-&gt;val));
        serialize(root-&gt;left, s);
        serialize(root-&gt;right, s);
    }
    
    TreeNode* deserialize(const string&amp; s, int&amp; pos, int curMin, int curMax) {
        if (pos &gt;= s.size()) return nullptr;
        int val = *reinterpret_cast&lt;const int*&gt;(s.data() + pos);
        if (val &lt; curMin || val &gt; curMax) return nullptr;
        pos += sizeof(val);
        TreeNode* root = new TreeNode(val);
        root-&gt;left = deserialize(s, pos, curMin, val);
        root-&gt;right = deserialize(s, pos, val, curMax);
        return root;
    }
};</pre><p>&nbsp;</p>
<p><strong>Related Problems</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/">[解题报告] LeetCode 297. Serialize and Deserialize Binary Tree</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-449-serialize-and-deserialize-bst/">花花酱 LeetCode 449. Serialize and Deserialize BST</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-449-serialize-and-deserialize-bst/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 297. Serialize and Deserialize Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 18 Sep 2017 02:55:45 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[serialization]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=316</guid>

					<description><![CDATA[<p>Problem: Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/">花花酱 LeetCode 297. Serialize and Deserialize Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/JL4OjKV_pGE?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p>
<p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p>
<p>For example, you may serialize the following tree</p><pre class="crayon-plain-tag">1
   / \
  2   3
     / \
    4   5</pre><p>as <code>"[1,2,3,null,null,4,5]"</code>, just the same as <a href="https://leetcode.com/faq/#binary-tree">how LeetCode OJ serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p>
<p><b>Note:</b> Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.</p>
<p><a href="https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/">https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/</a></p>
<p><strong>Idea:</strong></p>
<p>Recursion</p>
<p>Time Complexity O(n)</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1.png"><img class="alignnone size-full wp-image-321" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2.png"><img class="alignnone size-full wp-image-320" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/297-ep59-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<h1><strong>Solution 1: ASCII</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 39 ms
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        serialize(root, out);
        return out.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize(in);
    }
private:
    void serialize(TreeNode* root, ostringstream&amp; out) {
        if (!root) {
            out &lt;&lt; "# ";
            return;
        }        
        out &lt;&lt; root-&gt;val &lt;&lt; " ";
        serialize(root-&gt;left, out);
        serialize(root-&gt;right, out);
    }
    
    TreeNode* deserialize(istringstream&amp; in) {
        string val;
        in &gt;&gt; val;
        if (val == "#") return nullptr;        
        TreeNode* root = new TreeNode(stoi(val));        
        root-&gt;left = deserialize(in);
        root-&gt;right = deserialize(in);        
        return root;
    }
};</pre><p></div></div></p>
<h1><strong>Solution 2: Binary</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 23 ms (beat 98.07%)
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        serialize(root, out);
        return out.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize(in);
    }
private:
    enum STATUS {
        ROOT_NULL = 0x0,
        ROOT = 0x1,
        LEFT = 0x2,
        RIGHT = 0x4
    };
    
    void serialize(TreeNode* root, ostringstream&amp; out) {
        char status = 0;
        if (root) status |= ROOT;
        if (root &amp;&amp; root-&gt;left) status |= LEFT;
        if (root &amp;&amp; root-&gt;right) status |= RIGHT;
        out.write(&amp;status, sizeof(char));        
        if (!root) return;
        out.write(reinterpret_cast&lt;char*&gt;(&amp;(root-&gt;val)), sizeof(root-&gt;val));
        if (root-&gt;left) serialize(root-&gt;left, out);
        if (root-&gt;right) serialize(root-&gt;right, out);
    }
    
    TreeNode* deserialize(istringstream&amp; in) {
        char status;
        in.read(&amp;status, sizeof(char));
        if (!status &amp; ROOT) return nullptr;
        auto root = new TreeNode(0);
        in.read(reinterpret_cast&lt;char*&gt;(&amp;root-&gt;val), sizeof(root-&gt;val));        
        root-&gt;left = (status &amp; LEFT) ? deserialize(in) : nullptr;
        root-&gt;right = (status &amp; RIGHT) ? deserialize(in) : nullptr;
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));</pre><p></div><h2 class="tabtitle">C++ (string)</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 23 ms (&lt;98.13%)
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string s;
        serialize(root, s);
        return s;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) { 
        int pos = 0;
        return deserialize(data, pos);
    }
private:
    enum STATUS {
        ROOT_NULL = 0x0,
        ROOT = 0x1,
        LEFT = 0x2,
        RIGHT = 0x4
    };
    
    void serialize(TreeNode* root, string&amp; s) {
        char status = ROOT_NULL;
        if (root) status |= ROOT;
        if (root &amp;&amp; root-&gt;left) status |= LEFT;
        if (root &amp;&amp; root-&gt;right) status |= RIGHT;
        s.push_back(status);
        if (!root) return;
        s.append(reinterpret_cast&lt;char*&gt;(&amp;root-&gt;val), sizeof(root-&gt;val));
        if (root-&gt;left) serialize(root-&gt;left, s);
        if (root-&gt;right) serialize(root-&gt;right, s);
    }
    
    TreeNode* deserialize(const string&amp; s, int&amp; pos) {
        char status = s[pos++];
        if (!status) return nullptr;
        TreeNode* root = new TreeNode(0);
        memcpy(&amp;root-&gt;val, s.data() + pos, sizeof(root-&gt;val));
        pos += sizeof(root-&gt;val);  
        root-&gt;left = (status &amp; LEFT) ? deserialize(s, pos) : nullptr;
        root-&gt;right = (status &amp; RIGHT) ? deserialize(s, pos) : nullptr;
        return root;
    }
};</pre><p></div></div></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-449-serialize-and-deserialize-bst/">LeetCode 449. Serialize and Deserialize BST</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/">花花酱 LeetCode 297. Serialize and Deserialize Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-297-serialize-and-deserialize-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
