<?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>longest path Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/longest-path/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/longest-path/</link>
	<description></description>
	<lastBuildDate>Wed, 14 Oct 2020 19:41:16 +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>longest path Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/longest-path/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1617. Count Subtrees With Max Distance Between Cities</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1617-count-subtrees-with-max-distance-between-cities/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1617-count-subtrees-with-max-distance-between-cities/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Oct 2020 20:08:05 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[diameter]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[longest path]]></category>
		<category><![CDATA[tree]]></category>
		<category><![CDATA[tree dp]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7484</guid>

					<description><![CDATA[<p>There are&#160;n&#160;cities numbered from&#160;1&#160;to&#160;n. You are given an array&#160;edges&#160;of size&#160;n-1, where&#160;edges[i] = [ui, vi]&#160;represents a bidirectional edge between cities&#160;ui&#160;and&#160;vi. There exists a unique path between&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1617-count-subtrees-with-max-distance-between-cities/">花花酱 LeetCode 1617. Count Subtrees With Max Distance Between Cities</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1617. Count Subtrees With Max Distance Between Cities - 刷题找工作 EP362" width="500" height="281" src="https://www.youtube.com/embed/qag7m9VRf-A?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>There are&nbsp;<code>n</code>&nbsp;cities numbered from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>. You are given an array&nbsp;<code>edges</code>&nbsp;of size&nbsp;<code>n-1</code>, where&nbsp;<code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>]</code>&nbsp;represents a bidirectional edge between cities&nbsp;<code>u<sub>i</sub></code>&nbsp;and&nbsp;<code>v<sub>i</sub></code>. There exists a unique path between each pair of cities. In other words, the cities form a&nbsp;<strong>tree</strong>.</p>



<p>A&nbsp;<strong>subtree</strong>&nbsp;is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.</p>



<p>For each&nbsp;<code>d</code>&nbsp;from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n-1</code>, find the number of subtrees in which the&nbsp;<strong>maximum distance</strong>&nbsp;between any two cities in the subtree is equal to&nbsp;<code>d</code>.</p>



<p>Return&nbsp;<em>an array of size</em>&nbsp;<code>n-1</code>&nbsp;<em>where the&nbsp;</em><code>d<sup>th</sup></code><em>element&nbsp;<strong>(1-indexed)</strong>&nbsp;is the number of subtrees in which the&nbsp;<strong>maximum distance</strong>&nbsp;between any two cities is equal to&nbsp;</em><code>d</code>.</p>



<p><strong>Notice</strong>&nbsp;that&nbsp;the&nbsp;<strong>distance</strong>&nbsp;between the two cities is the number of edges in the path between them.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/09/21/p1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4, edges = [[1,2],[2,3],[2,4]]
<strong>Output:</strong> [3,4,0]
<strong>Explanation:
</strong>The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.
The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.
No subtree has two nodes where the max distance between them is 3.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2, edges = [[1,2]]
<strong>Output:</strong> [1]
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, edges = [[1,2],[2,3]]
<strong>Output:</strong> [2,1]
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>2 &lt;= n &lt;= 15</code></li><li><code>edges.length == n-1</code></li><li><code>edges[i].length == 2</code></li><li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub>&nbsp;&lt;= n</code></li><li>All pairs&nbsp;<code>(u<sub>i</sub>, v<sub>i</sub>)</code>&nbsp;are distinct.</li></ul>



<h2><strong>Solution1: Brute Force</strong> <strong>+ Diameter of tree</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362.png" alt="" class="wp-image-7500" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Try all subtrees and find the diameter of that subtree (longest distance between any node)</p>



<p>Time complexity: O(2^n * 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
class Solution {
public:
  vector&lt;int&gt; countSubgraphsForEachDiameter(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges, int last = -1) {
    vector&lt;vector&lt;int&gt;&gt; g(n);
    for (const auto&amp; e : edges)
      g[e[0] - 1].push_back(e[1] - 1), g[e[1] - 1].push_back(e[0] - 1);
    
    vector&lt;int&gt; seen(n, -1), seen2;
    queue&lt;int&gt; q;
    
    auto bfs = [&amp;](int start, vector&lt;int&gt;&amp; seen) -&gt; pair&lt;int, int&gt; {
      q.push(start);
      seen[start] = 1;
      int count = 0, dist = -1;
      while (!q.empty()) {
        int s = q.size();        
        while (s--) {
          last = q.front(); q.pop();
          ++count;
          for (int v : g[last])
            if (seen[v] != -1 &amp;&amp; !seen[v]++) q.push(v);
        }
        ++dist;
      }
      return {dist, count};
    };
    
    vector&lt;int&gt; ans(n - 1);
    for (int s = 0; s &lt; 1 &lt;&lt; n; ++s) {
      if (__builtin_popcount(s) &lt;= 1) continue;
      fill(begin(seen), end(seen), -1);
      for (int i = 0; i &lt; n; ++i) if (s &amp; (1 &lt;&lt; i)) seen[i] = 0;
      seen2 = seen;
      const int start = 31 - __builtin_clz(s &amp; (s - 1));
      if (bfs(start, seen).second != __builtin_popcount(s)) continue;      
      ++ans[bfs(last, seen2).first - 1];
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: DP on Trees</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-2.png" alt="" class="wp-image-7501" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-3.png" alt="" class="wp-image-7502" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-4.png" alt="" class="wp-image-7503" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-4-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-5.png" alt="" class="wp-image-7504" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-5.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-5-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-5-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-6.png" alt="" class="wp-image-7505" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-6.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-6-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-6-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-7.png" alt="" class="wp-image-7506" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-7.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-7-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-7-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-8.png" alt="" class="wp-image-7507" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-8.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-8-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-8-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-9.png" alt="" class="wp-image-7508" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-9.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-9-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/1617-ep362-9-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>dp[i][k][d] := # of subtrees rooted at i with tree diameter of d and the distance from i to the farthest node is k.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua, 4ms, 8.8MB
class Solution {
public:
  vector&lt;int&gt; countSubgraphsForEachDiameter(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {    
    vector&lt;vector&lt;int&gt;&gt; g(n);
    for (const auto&amp; e : edges) {
      g[e[0] - 1].push_back(e[1] - 1);
      g[e[1] - 1].push_back(e[0] - 1);
    }
    vector&lt;vector&lt;vector&lt;int&gt;&gt;&gt; dp(n);    
    vector&lt;int&gt; sizes(n);
    function&lt;void(int, int)&gt; dfs = [&amp;](int u, int p) {
      if (!dp[u].empty()) return;      
      dp[u] = vector&lt;vector&lt;int&gt;&gt;(n, vector&lt;int&gt;(n));
      dp[u][0][0] = 1;
      sizes[u] = 1;
      for (int v : g[u]) {
        if (v == p) continue;
        dfs(v, u);
        vector&lt;vector&lt;int&gt;&gt; dpu(dp[u]);
        for (int d1 = 0; d1 &lt; sizes[u]; ++d1)
          for (int k1 = 0; k1 &lt;= d1; ++k1) {
            if (!dp[u][k1][d1]) continue;
            for (int d2 = 0; d2 &lt; sizes[v]; ++d2)
              for (int k2 = 0; k2 &lt;= d2; ++k2) {
                const int d = max({d1, d2, k1 + k2 + 1});
                const int k = max(k1, k2 + 1);
                dpu[k][d] += dp[u][k1][d1] * dp[v][k2][d2];
              }
          }
        swap(dpu, dp[u]);
        sizes[u] += sizes[v];
      }
    };
    vector&lt;int&gt; ans(n - 1);
    dfs(0, -1);
    for (int i = 0; i &lt; n; ++i) 
      for (int k = 0; k &lt; n; ++k)
        for (int d = 1; d &lt; n; ++d)
          ans[d - 1] += dp[i][k][d];
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1617-count-subtrees-with-max-distance-between-cities/">花花酱 LeetCode 1617. Count Subtrees With Max Distance Between Cities</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-1617-count-subtrees-with-max-distance-between-cities/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1372. Longest ZigZag Path in a Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1372-longest-zigzag-path-in-a-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1372-longest-zigzag-path-in-a-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Mar 2020 08:53:52 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[longest path]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6405</guid>

					<description><![CDATA[<p>Given a binary tree&#160;root, a&#160;ZigZag path for a binary tree is defined as follow: Choose&#160;any&#160;node in the binary tree and a direction (right or left).&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1372-longest-zigzag-path-in-a-binary-tree/">花花酱 LeetCode 1372. Longest ZigZag Path in 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[
<p>Given a binary tree&nbsp;<code>root</code>, a&nbsp;ZigZag path for a binary tree is defined as follow:</p>



<ul><li>Choose&nbsp;<strong>any&nbsp;</strong>node in the binary tree and a direction (right or left).</li><li>If the current direction is right then move to the right child of the current node otherwise move to the left child.</li><li>Change the direction from right to left or right to left.</li><li>Repeat the second and third step until you can&#8217;t move in the tree.</li></ul>



<p>Zigzag length is defined as the number of nodes visited &#8211; 1. (A single node has a length of 0).</p>



<p>Return&nbsp;the longest&nbsp;<strong>ZigZag</strong>&nbsp;path contained in that tree.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/01/22/sample_1_1702.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Longest ZigZag path in blue nodes (right -&gt; left -&gt; right).
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/01/22/sample_2_1702.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,1,1,null,1,null,null,1,1,null,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> Longest ZigZag path in blue nodes (left -&gt; right -&gt; left -&gt; right).
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1]
<strong>Output:</strong> 0
</pre>



<p><strong>Constraints:</strong></p>



<ul><li>Each tree has at most&nbsp;<code>50000</code>&nbsp;nodes..</li><li>Each node&#8217;s value is between&nbsp;<code>[1, 100]</code>.</li></ul>



<h2><strong>Solution: Recursion</strong></h2>



<p>For each node return <br>1. max ZigZag length if go left<br>2. max ZigZag length if go right<br>3. maz ZigZag length within the subtree<br><br>ZigZag(root):<br>  ll, lr, lm = ZigZag(root.left)<br>  rl, rr, rm = ZigZag(root.right)<br>return (lr+1, rl + 1, max(lr+1, rl+1, lm, rm))</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestZigZag(TreeNode* root) {    
    return get&lt;2&gt;(ZigZag(root));
  }
    
  // Returns {left, right, max}
  tuple&lt;int, int, int&gt; ZigZag(TreeNode* root) {
    if (!root) return {-1, -1, -1};
    auto [ll, lr, lm] = ZigZag(root-&gt;left);
    auto [rl, rr, rm] = ZigZag(root-&gt;right);
    int l = lr + 1;
    int r = rl + 1;
    return {l, r, max({l, r, lm, rm})};
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def longestZigZag(self, root: TreeNode) -&gt; int:
    def ZigZag(node):
      if not node: return (-1, -1, -1)
      ll, lr, lm = ZigZag(node.left)
      rl, rr, rm = ZigZag(node.right)
      return (lr + 1, rl + 1, max(lr + 1, rl + 1, lm, rm))
    return ZigZag(root)[2]</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1372-longest-zigzag-path-in-a-binary-tree/">花花酱 LeetCode 1372. Longest ZigZag Path in 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-1372-longest-zigzag-path-in-a-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
