<?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>postorder Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/postorder/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/postorder/</link>
	<description></description>
	<lastBuildDate>Sun, 19 Jul 2020 06:45:12 +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>postorder Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/postorder/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 19 Jul 2020 05:14:52 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[postorder]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7119</guid>

					<description><![CDATA[<p>Given a tree (i.e. a connected, undirected graph that has no cycles) consisting of&#160;n&#160;nodes numbered from&#160;0&#160;to&#160;n - 1&#160;and exactly&#160;n - 1&#160;edges. The&#160;root&#160;of the tree is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/">花花酱 LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label</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 tree (i.e. a connected, undirected graph that has no cycles) consisting of&nbsp;<code>n</code>&nbsp;nodes numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;and exactly&nbsp;<code>n - 1</code>&nbsp;<code>edges</code>. The&nbsp;<strong>root</strong>&nbsp;of the tree is the node&nbsp;<code>0</code>, and each node of the tree has&nbsp;<strong>a label</strong>&nbsp;which is a lower-case character given in the string&nbsp;<code>labels</code>&nbsp;(i.e. The node with the number&nbsp;<code>i</code>&nbsp;has the label&nbsp;<code>labels[i]</code>).</p>



<p>The&nbsp;<code>edges</code>&nbsp;array is given on the form&nbsp;<code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>, which means there is an edge between nodes&nbsp;<code>a<sub>i</sub></code>&nbsp;and&nbsp;<code>b<sub>i</sub></code>&nbsp;in the tree.</p>



<p>Return&nbsp;<em>an array of size&nbsp;<code>n</code></em>&nbsp;where&nbsp;<code>ans[i]</code>&nbsp;is the number of nodes in the subtree of the&nbsp;<code>i<sup>th</sup></code>&nbsp;node which have the same label as node&nbsp;<code>i</code>.</p>



<p>A&nbsp;subtree&nbsp;of a tree&nbsp;<code>T</code>&nbsp;is the tree consisting of a node in&nbsp;<code>T</code>&nbsp;and all of its descendant&nbsp;nodes.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/07/01/q3e1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
<strong>Output:</strong> [2,1,1,1,1,1,1]
<strong>Explanation:</strong> Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/07/01/q3e2.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
<strong>Output:</strong> [4,2,1,1]
<strong>Explanation:</strong> The sub-tree of node 2 contains only node 2, so the answer is 1.
The sub-tree of node 3 contains only node 3, so the answer is 1.
The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/07/01/q3e3.jpg" alt=""/></figure>



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



<p><strong>Example 4:</strong></p>



<pre class="crayon-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; n = 6, edges = [[0,1],[0,2],[1,3],[3,4],[4,5]], labels = &quot;cbabaa&quot;
&lt;strong&gt;Output:&lt;/strong&gt; [1,2,1,1,2,1]</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, edges = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6]], labels = "aaabaaa"
<strong>Output:</strong> [6,5,4,1,3,2,1]
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 10^5</code></li><li><code>edges.length == n - 1</code></li><li><code>edges[i].length == 2</code></li><li><code>0 &lt;= a<sub>i</sub>,&nbsp;b<sub>i</sub>&nbsp;&lt; n</code></li><li><code>a<sub>i</sub>&nbsp;!=&nbsp;b<sub>i</sub></code></li><li><code>labels.length == n</code></li><li><code>labels</code>&nbsp;is consisting of only of lower-case English letters.</li></ul>



<h2><strong>Solution: Post order traversal + hashtable</strong></h2>



<p>For each label, record the count. When visiting a node, we first record the current count of its label as before, and traverse its children, when done, increment the current count, ans[i] = current &#8211;  before.</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
class Solution {
public:
  vector&lt;int&gt; countSubTrees(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges, 
                            string_view labels) {
    vector&lt;vector&lt;int&gt;&gt; g(n);    
    for (const auto&amp; e : edges) {
      g[e[0]].push_back(e[1]);
      g[e[1]].push_back(e[0]);
    }
    vector&lt;int&gt; seen(n);
    vector&lt;int&gt; count(26);
    vector&lt;int&gt; ans(n);
    function&lt;void(int)&gt; postOrder = [&amp;](int i) {
      if (seen[i]++) return;
      int before = count[labels[i] - 'a'];
      for (int j : g[i]) postOrder(j);        
      ans[i] = ++count[labels[i] - 'a'] - before;
    };
    postOrder(0);
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  private List&lt;List&lt;Integer&gt;&gt; g;
  private String labels;
  private int[] ans;
  private int[] seen;
  private int[] count;
  
  public int[] countSubTrees(int n, int[][] edges, String labels) {
    this.g = new ArrayList&lt;List&lt;Integer&gt;&gt;(n);
    this.labels = labels; 
    for (int i = 0; i &lt; n; ++i)
      this.g.add(new ArrayList&lt;Integer&gt;());
    for (int[] e : edges) {
      this.g.get(e[0]).add(e[1]);
      this.g.get(e[1]).add(e[0]);
    }
    this.ans = new int[n];
    this.seen = new int[n];
    this.count = new int[26];
    this.postOrder(0);
    return ans;
  }
  
  private void postOrder(int i) {
    if (this.seen[i]++ &gt; 0) return;
    int before = this.count[this.labels.charAt(i) - 'a'];
    for (int j : this.g.get(i)) this.postOrder(j);
    this.ans[i] = ++this.count[this.labels.charAt(i) - 'a'] - before;    
  }
}</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def countSubTrees(self, n: int, edges: List[List[int]], 
                    labels: str) -&gt; List[int]:
    g = [[] for _ in range(n)]
    for u, v in edges:
      g[u].append(v)
      g[v].append(u)
    seen = [False] * n
    count = [0] * 26
    ans = [0] * n
    def postOrder(i):
      if seen[i]: return
      seen[i] = True
      before = count[ord(labels[i]) - ord('a')]
      for j in g[i]: postOrder(j)
      count[ord(labels[i]) - ord('a')] += 1
      ans[i] = count[ord(labels[i]) - ord('a')] - before
    postOrder(0)
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/">花花酱 LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label</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-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-889-construct-binary-tree-from-preorder-and-postorder-traversal/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-889-construct-binary-tree-from-preorder-and-postorder-traversal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 23 Aug 2018 08:08:39 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[postorder]]></category>
		<category><![CDATA[preorder]]></category>
		<category><![CDATA[reconstruct]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3675</guid>

					<description><![CDATA[<p>Problem Return any binary tree that matches the given preorder and postorder traversals. Values in the traversals pre and post are distinct positive integers. Example 1: Input: pre = [1,2,4,5,3,6,7],&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-889-construct-binary-tree-from-preorder-and-postorder-traversal/">花花酱 LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal</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/53aOi0Drp9I?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Return any binary tree that matches the given preorder and postorder traversals.</p>
<p>Values in the traversals <code>pre</code> and <code>post</code> are distinct positive integers.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>pre = <span id="example-input-1-1">[1,2,4,5,3,6,7]</span>, post = <span id="example-input-1-2">[4,5,2,6,7,3,1]</span>
<strong>Output: </strong><span id="example-output-1">[1,2,3,4,5,6,7]</span>
</pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>1 &lt;= pre.length == post.length &lt;= 30</code></li>
<li><code>pre[]</code> and <code>post[]</code> are both permutations of <code>1, 2, ..., pre.length</code>.</li>
<li>It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.</li>
</ul>
<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"></ins></p>
<p><img class="alignnone size-full wp-image-3688" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/889-ep219.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/889-ep219.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/889-ep219-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/889-ep219-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution: Recursion</strong></h1>
<p>pre = [(root) (left-child) (right-child)]</p>
<p>post = [(left-child) (right-child) (root)]</p>
<p>We need to recursively find the first node in pre.left-child from post.left-child</p>
<p>e.g.</p>
<p><span id="example-input-1-1">pre = [(<span style="color: #0000ff;"><strong>1</strong></span>), (<span style="color: #ff0000;"><strong>2</strong></span>,4,5), (3,6,7)]</span></p>
<p>post = <span id="example-input-1-2">[(4,5,<strong><span style="color: #ff0000;">2</span></strong>), (6,7,3), (<span style="color: #0000ff;"><strong>1</strong></span>)]</span></p>
<p>First element of left-child is 2 and the length of it is 3.</p>
<p>root = new TreeNode(1)<br />
root.left = build((2,4,5), (4,5,2))<br />
root.right = build((3,6,7), (6,7,3))</p>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  TreeNode* constructFromPrePost(vector&lt;int&gt;&amp; pre, vector&lt;int&gt;&amp; post) {
    return constructFromPrePost(cbegin(pre), cend(pre), cbegin(post), cend(post));
  }
private:
  typedef vector&lt;int&gt;::const_iterator VIT;
  TreeNode* constructFromPrePost(VIT pre_l, VIT pre_r, VIT post_l, VIT post_r) {
    if (pre_l == pre_r) return nullptr;
    TreeNode* root = new TreeNode(*pre_l);
    ++pre_l;
    --post_r;
    if (pre_l == pre_r) return root;
    VIT post_m = next(find(post_l, post_r, *pre_l));
    VIT pre_m = pre_l + (post_m - post_l);
    root-&gt;left = constructFromPrePost(pre_l, pre_m, post_l, post_m);
    root-&gt;right = constructFromPrePost(pre_m, pre_r, post_m, post_r);
    return root;
  }
};</pre><p>Time complexity: O(n^2)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 60 ms
"""
class Solution:
  def constructFromPrePost(self, pre, post):
    def build(i, j, n):
      if n &lt;= 0: return None
      root = TreeNode(pre[i])
      if n == 1: return root
      k = j      
      while post[k] != pre[i + 1]: k += 1
      l = k - j + 1      
      root.left = build(i + 1, j, l)
      root.right = build(i + l + 1, k + 1, n - l - 1)
      return root
    return build(0, 0, len(pre))</pre><p>Time complexity: O(n)</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 52 ms (beats 100%)
"""
class Solution:
  def constructFromPrePost(self, pre, post):    
    def build(i, j, n):
      if n &lt;= 0: return None
      root = TreeNode(pre[i])
      if n == 1: return root
      k = index[pre[i + 1]]      
      l = k - j + 1      
      root.left = build(i + 1, j, l)
      root.right = build(i + l + 1, k + 1, n - l - 1)
      return root
    index = {}
    for i in range(len(pre)):
      index[post[i]] = i
    return build(0, 0, len(pre))</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-889-construct-binary-tree-from-preorder-and-postorder-traversal/">花花酱 LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal</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-889-construct-binary-tree-from-preorder-and-postorder-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 590. N-ary Tree Postorder Traversal</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-590-n-ary-tree-postorder-traversal/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-590-n-ary-tree-postorder-traversal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 13 Jul 2018 06:24:56 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[n-ary]]></category>
		<category><![CDATA[postorder]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3113</guid>

					<description><![CDATA[<p>Problem Given an n-ary tree, return the postorder traversal of its nodes&#8217; values. &#160; For example, given a 3-ary tree: &#160; Return its postorder traversal as: [5,6,3,2,4,1]. &#160; Note: Recursive solution&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-590-n-ary-tree-postorder-traversal/">花花酱 LeetCode 590. N-ary Tree Postorder Traversal</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>Given an n-ary tree, return the <i>postorder</i> traversal of its nodes&#8217; values.</p>
<p>&nbsp;</p>
<p>For example, given a <code>3-ary</code> tree:</p>
<p><img src="https://leetcode.com/static/images/problemset/NaryTreeExample.png" width="40%" height="40%" /></p>
<p>&nbsp;</p>
<p>Return its postorder traversal as: <code>[5,6,3,2,4,1]</code>.</p>
<p>&nbsp;</p>
<p><b>Note:</b> Recursive solution is trivial, could you do it iteratively?</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"> </ins></p>
<h1><strong>Solution 1: Recursive</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: 44 ms
class Solution {
public:
  vector&lt;int&gt; postorder(Node* root) {
    vector&lt;int&gt; ans;
    postorder(root, ans);
    return ans;
  }
private:
  void postorder(Node* root, vector&lt;int&gt;&amp; ans) {
    if (!root) return;
    for (auto child : root-&gt;children)
      postorder(child, ans);
    ans.push_back(root-&gt;val);
  }
};</pre><p></div></div></p>
<h1><strong>Solution 2: Iterative</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: 44 ms
class Solution {
public:
  vector&lt;int&gt; postorder(Node* root) {
   if (!root) return {};
    vector&lt;int&gt; ans;
    stack&lt;Node*&gt; s;
    s.push(root);
    while (!s.empty()) {
      const Node* node = s.top(); s.pop();      
      ans.push_back(node-&gt;val);
      for (auto child : node-&gt;children)
        s.push(child);      
    }
    reverse(begin(ans), end(ans));
    return ans;
  }
};</pre><p></div></div></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-589-n-ary-tree-preorder-traversal/">花花酱 LeetCode 589. N-ary Tree Preorder Traversal</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/">花花酱 LeetCode 145. Binary Tree Postorder Traversal</a></li>
<li><a href="http://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/">花花酱 LeetCode 102. Binary Tree Level Order Traversal</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-590-n-ary-tree-postorder-traversal/">花花酱 LeetCode 590. N-ary Tree Postorder Traversal</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-590-n-ary-tree-postorder-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 332. Reconstruct Itinerary</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-332-reconstruct-itinerary/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-332-reconstruct-itinerary/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 13 Sep 2017 02:34:04 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[postorder]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=252</guid>

					<description><![CDATA[<p>Problem: Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-332-reconstruct-itinerary/">花花酱 LeetCode 332. Reconstruct Itinerary</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/4udFSOWQpdg?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem</strong>:</p>
<p>Given a list of airline tickets represented by pairs of departure and arrival airports <code>[from, to]</code>, reconstruct the itinerary in order. All of the tickets belong to a man who departs from <code>JFK</code>. Thus, the itinerary must begin with <code>JFK</code>.</p>
<p><b>Note:</b></p>
<ol>
<li>If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary <code>["JFK", "LGA"]</code> has a smaller lexical order than <code>["JFK", "LGB"]</code>.</li>
<li>All airports are represented by three capital letters (IATA code).</li>
<li>You may assume all tickets form at least one valid itinerary.</li>
</ol>
<p><b>Example 1:</b><br />
<code>tickets</code> = <code>[["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]</code><br />
Return <code>["JFK", "MUC", "LHR", "SFO", "SJC"]</code>.</p>
<p><b>Example 2:</b><br />
<code>tickets</code> = <code>[["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]</code><br />
Return <code>["JFK","ATL","JFK","SFO","ATL","SFO"]</code>.<br />
Another possible reconstruction is <code>["JFK","SFO","ATL","JFK","ATL","SFO"]</code>. But it is larger in lexical order.</p>
<p>&nbsp;</p>
<p><strong>Idea</strong>:</p>
<p>Convert the graph to a tree and do post-order traversal</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-1.png"><img class="alignnone size-full wp-image-257" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a><img class="alignnone size-full wp-image-256" style="font-size: 1rem;" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-3.png"><img class="alignnone size-full wp-image-255" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-3-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/332-ep52-3-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong> Solution:</strong></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 13 ms
class Solution {
public:
    vector&lt;string&gt; findItinerary(vector&lt;pair&lt;string, string&gt;&gt; tickets) {
        route_.clear();
        trips_.clear();
        
        for(const auto&amp; pair : tickets)
            trips_[pair.first].push_back(pair.second);
        
        for(auto&amp; pair : trips_) {
            auto&amp; dests = pair.second;
            std::sort(dests.begin(), dests.end());
        }
        
        const string kStart = "JFK";
        
        visit(kStart);
        
        return vector&lt;string&gt;(route_.crbegin(), route_.crend());
    }
private:
    // src -&gt; {dst1, dest2, ..., destn}
    unordered_map&lt;string, deque&lt;string&gt;&gt; trips_;    
    // ans (reversed)
    vector&lt;string&gt; route_;
    
    void visit(const string&amp; src) {
        auto&amp; dests = trips_[src];
        while (!dests.empty()) {
            // Get the smallest dest
            const string dest = dests.front();
            // Remove the ticket
            dests.pop_front();
            // Visit dest
            visit(dest);
        }
        // Add current node to the route
        route_.push_back(src);
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-332-reconstruct-itinerary/">花花酱 LeetCode 332. Reconstruct Itinerary</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/graph/leetcode-332-reconstruct-itinerary/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 145. Binary Tree Postorder Traversal</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 08 Sep 2017 08:19:18 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[inorder]]></category>
		<category><![CDATA[iterative]]></category>
		<category><![CDATA[leetcode]]></category>
		<category><![CDATA[postorder]]></category>
		<category><![CDATA[preorder]]></category>
		<category><![CDATA[recursive]]></category>
		<category><![CDATA[solutions]]></category>
		<category><![CDATA[traversal]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=150</guid>

					<description><![CDATA[<p>Problem: Given a binary tree, return the postorder traversal of its nodes&#8217; values. For example: Given binary tree {1,#,2,3}, [crayon-663a0c7bc29b2703857052/] return [3,2,1]. Note: Recursive solution is trivial, could you do&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/">花花酱 LeetCode 145. Binary Tree Postorder Traversal</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/A6iCX_5xiU4?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem:</strong></h1>
<p>Given a binary tree, return the <i>postorder</i> traversal of its nodes&#8217; values.</p>
<p>For example:<br />
Given binary tree <code>{1,#,2,3}</code>,</p><pre class="crayon-plain-tag">1
    \
     2
    /
   3</pre><p>return <code>[3,2,1]</code>.</p>
<p><b>Note:</b> Recursive solution is trivial, could you do it iteratively?</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1.png"><img class="alignnone size-full wp-image-154" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2.png"><img class="alignnone size-full wp-image-153" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<h1><strong>Solution 1:</strong></h1>
<p></p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    vector&lt;int&gt; postorderTraversal(TreeNode* root) {
        vector&lt;int&gt; ans;        
        postorderTraversal(root, ans);
        return ans;
    }
    
    void postorderTraversal(TreeNode* root, vector&lt;int&gt;&amp; ans) {
        if (!root) return;
        postorderTraversal(root-&gt;left, ans);
        postorderTraversal(root-&gt;right, ans);
        ans.push_back(root-&gt;val);
    }
};</pre><p></p>
<h1><strong>Solution 2:</strong></h1>
<p></p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    vector&lt;int&gt; postorderTraversal(TreeNode* root) {
        if (!root) return {};
        vector&lt;int&gt; ans;
        const vector&lt;int&gt; l = postorderTraversal(root-&gt;left);
        const vector&lt;int&gt; r = postorderTraversal(root-&gt;right);
        ans.insert(ans.end(), l.begin(), l.end());
        ans.insert(ans.end(), r.begin(), r.end());
        ans.push_back(root-&gt;val);
        return ans;
    }
};</pre><p></p>
<h1><strong>Solution 3:</strong></h1>
<p></p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    vector&lt;int&gt; postorderTraversal(TreeNode* root) {
        if (!root) return {};
        deque&lt;int&gt; ans;
        stack&lt;TreeNode*&gt; s;
        s.push(root);
        while (!s.empty()) {
            TreeNode* n = s.top();
            s.pop();
            ans.push_front(n-&gt;val); // O(1)
            if (n-&gt;left) s.push(n-&gt;left);
            if (n-&gt;right) s.push(n-&gt;right);
        }   
        return vector&lt;int&gt;(ans.begin(), ans.end());
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/">花花酱 LeetCode 145. Binary Tree Postorder Traversal</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-145-binary-tree-postorder-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
