<?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>subtree Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/subtree/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/subtree/</link>
	<description></description>
	<lastBuildDate>Wed, 08 May 2019 03:42:49 +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>subtree Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/subtree/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 865. Smallest Subtree with all the Deepest Nodes</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-865-smallest-subtree-with-all-the-deepest-nodes/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-865-smallest-subtree-with-all-the-deepest-nodes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Jul 2018 15:55:55 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[depth]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subtree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3018</guid>

					<description><![CDATA[<p>Problem Given a binary tree rooted at root, the depth of each node is the shortest distance to the root. A node is deepest if it has the largest depth&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-865-smallest-subtree-with-all-the-deepest-nodes/">花花酱 LeetCode 865. Smallest Subtree with all the Deepest Nodes</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/q1zk8vZIDw0?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Given a binary tree rooted at <code>root</code>, the <em>depth</em> of each node is the shortest distance to the root.</p>
<p>A node is <em>deepest</em> if it has the largest depth possible among any node in the <u>entire tree</u>.</p>
<p>The subtree of a node is that node, plus the set of all descendants of that node.</p>
<p>Return the node with the largest depth such that it contains all the deepest nodes in it&#8217;s subtree.</p>
<p>&nbsp;</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false "><strong>Input: </strong><span id="example-input-1-1">[3,5,1,6,2,0,8,null,null,7,4]</span>
<strong>Output: </strong><span id="example-output-1">[2,7,4]</span>
<strong>Explanation:
</strong>
<img src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" alt="" />

We return the node with value 2, colored in yellow in the diagram.
The nodes colored in blue are the deepest nodes of the tree.
The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a serialization of the given tree.
The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2.
Both the input and output have TreeNode type.
</pre>
<p>&nbsp;</p>
<p><strong>Note:</strong></p>
<ul>
<li>The number of nodes in the tree will be between 1 and 500.</li>
<li>The values of each node are unique.</li>
</ul>
<p>&nbsp;</p>
<p><ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-2404451723245401"
     data-ad-slot="7983117522"><br />
</ins></p>
<p><img class="alignnone size-full wp-image-3022" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/866-ep204.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/866-ep204.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/866-ep204-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/866-ep204-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution: Recursion</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 0 ms
class Solution {
public:
  TreeNode* subtreeWithAllDeepest(TreeNode* root) {
    return depth(root).second;
  }
private:
  pair&lt;int, TreeNode*&gt; depth(TreeNode* root) {
    if (root == nullptr)
      return {-1, nullptr};
    auto l = depth(root-&gt;left);
    auto r = depth(root-&gt;right);
    int dl = l.first;
    int dr = r.first;
    return { max(dl, dr) + 1, 
             dl == dr ? root : (dl &gt; dr) ? l.second : r.second};
  }
};</pre><p>v2</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 0 ms
class Solution {
public:
  TreeNode* subtreeWithAllDeepest(TreeNode* root) {
    TreeNode* ans;
    depth(root, &amp;ans);
    return ans;
  }
private:
  int depth(TreeNode* root, TreeNode** s) {
    if (root == nullptr)
      return -1;
    TreeNode* sl;
    TreeNode* sr;
    int l = depth(root-&gt;left, &amp;sl);
    int r = depth(root-&gt;right, &amp;sr);
    *s = (l == r) ? root : ((l &gt; r) ? sl : sr);
    return max(l, r) + 1;
  }
};</pre><p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 40 ms
"""
class Solution:
  def subtreeWithAllDeepest(self, root):
    def solve(root):
      if not root: return (-1, None)
      dl, sl = solve(root.left)
      dr, sr = solve(root.right)
      if dl == dr: return (dl + 1, root)
      return (dl + 1, sl) if dl &gt; dr else (dr + 1, sr)
    return solve(root)[1]</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-865-smallest-subtree-with-all-the-deepest-nodes/">花花酱 LeetCode 865. Smallest Subtree with all the Deepest Nodes</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-865-smallest-subtree-with-all-the-deepest-nodes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 572. Subtree of Another Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-572-subtree-of-another-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-572-subtree-of-another-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 20 Mar 2018 04:34:25 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[same tree]]></category>
		<category><![CDATA[subtree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2239</guid>

					<description><![CDATA[<p>Problem 题目大意：判断一棵树是不是另外一棵树的子树。 https://leetcode.com/problems/subtree-of-another-tree/description/ Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-572-subtree-of-another-tree/">花花酱 LeetCode 572. Subtree of Another 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/subtree-of-another-tree/description/">https://leetcode.com/problems/subtree-of-another-tree/description/</a></p>
<p>Given two non-empty binary trees <b>s</b> and <b>t</b>, check whether tree <b>t</b> has exactly the same structure and node values with a subtree of <b>s</b>. A subtree of <b>s</b> is a tree consists of a node in <b>s</b> and all of this node&#8217;s descendants. The tree <b>s</b> could also be considered as a subtree of itself.</p>
<p><b>Example 1:</b><br />
Given tree s:</p><pre class="crayon-plain-tag">3
    / \
   4   5
  / \
 1   2</pre><p>Given tree t:</p><pre class="crayon-plain-tag">4 
  / \
 1   2</pre><p>Return <b>true</b>, because t has the same structure and node values with a subtree of s.</p>
<p><b>Example 2:</b><br />
Given tree s:</p><pre class="crayon-plain-tag">3
    / \
   4   5
  / \
 1   2
    /
   0</pre><p>Given tree t:</p><pre class="crayon-plain-tag">4
  / \
 1   2</pre><p>Return <b>false</b>.</p>
<h1>Solution: Recursion</h1>
<p>Time complexity: O(max(n, m))</p>
<p>Space complexity: O(max(n, m))</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 29 ms
class Solution {
public:
  bool isSubtree(TreeNode* s, TreeNode* t) {
    if (t == nullptr) return true;
    if (s == nullptr) return false;
    if (isSameTree(s, t)) return true;
    return isSubtree(s-&gt;left, t) || isSubtree(s-&gt;right, t);
  }
private:
  bool isSameTree(TreeNode* s, TreeNode* t) {
    if (s == nullptr &amp;&amp; t == nullptr) return true;
    if (s == nullptr || t == nullptr) return false;
    return (s-&gt;val == t-&gt;val) 
           &amp;&amp; isSameTree(s-&gt;left, t-&gt;left) 
           &amp;&amp; isSameTree(s-&gt;right, t-&gt;right);
  }
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-100-same-tree/">[解题报告] Leetcode 100. Same Tree</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-508-most-frequent-subtree-sum/">花花酱 LeetCode 508. Most Frequent Subtree Sum</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-563-binary-tree-tilt/">花花酱 LeetCode 563. Binary Tree Tilt</a></li>
</ul>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-572-subtree-of-another-tree/">花花酱 LeetCode 572. Subtree of Another 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-572-subtree-of-another-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 508. Most Frequent Subtree Sum</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-508-most-frequent-subtree-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-508-most-frequent-subtree-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 03 Mar 2018 06:45:31 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[most frequent]]></category>
		<category><![CDATA[subtree]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1919</guid>

					<description><![CDATA[<p>&#160; Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-508-most-frequent-subtree-sum/">花花酱 LeetCode 508. Most Frequent Subtree Sum</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>&nbsp;</p>
<p>Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.</p>
<p><b>Examples 1</b><br />
Input:</p><pre class="crayon-plain-tag">5
 /  \
2   -3</pre><p>return [2, -3, 4], since all the values happen only once, return all of them in any order.</p>
<p><b>Examples 2</b><br />
Input:</p><pre class="crayon-plain-tag">5
 /  \
2   -5</pre><p>return [2], since 2 happens twice, however -5 only occur once.</p>
<p><b>Note:</b> You may assume the sum of values in any subtree is in the range of 32-bit signed integer.</p>
<p>&nbsp;</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 18 ms
class Solution {
public:
  vector&lt;int&gt; findFrequentTreeSum(TreeNode* root) {
    unordered_map&lt;int, int&gt; freqs;
    int max_freq = -1;
    vector&lt;int&gt; ans;
    (void)treeSum(root, freqs, max_freq, ans);
    return ans;
  }
private:
  int treeSum(TreeNode* root, unordered_map&lt;int, int&gt;&amp; freqs, int&amp; max_freq, vector&lt;int&gt;&amp; ans) {
    if (!root) return 0;
    int sum = root-&gt;val + 
              treeSum(root-&gt;left, freqs, max_freq, ans) + 
              treeSum(root-&gt;right, freqs, max_freq, ans);
    int freq = ++freqs[sum];
    if (freq &gt; max_freq) {
      max_freq = freq;
      ans.clear();
    }
    if (freq == max_freq)
      ans.push_back(sum);
    return sum;
  }
};</pre><p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 72 ms (beats 100%)
"""
class Solution:
  def findFrequentTreeSum(self, root):   
    if not root: return []
    
    def treeSum(root):
      if not root: return 0
      s = root.val + treeSum(root.left) + treeSum(root.right)
      f[s] += 1   
      return s
    f = collections.Counter()
    treeSum(root)    
    max_freq = max(f.values())        
    return [s for s in f.keys() if f[s] == max_freq]</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-508-most-frequent-subtree-sum/">花花酱 LeetCode 508. Most Frequent Subtree Sum</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-508-most-frequent-subtree-sum/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>
	</channel>
</rss>
