<?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>traversal Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/traversal/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/traversal/</link>
	<description></description>
	<lastBuildDate>Fri, 10 Dec 2021 05:21:20 +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>traversal Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/traversal/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 117. Populating Next Right Pointers in Each Node II</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 08:14:24 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[level order]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8933</guid>

					<description><![CDATA[<p>Given a binary tree [crayon-663c90f9bc69e886254852/] Populate each next pointer to point to its next right node. If there is no next right node, the next&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/">花花酱 LeetCode 117. Populating Next Right Pointers in Each Node II</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</p>



<pre class="crayon-plain-tag">struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}</pre>



<p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to&nbsp;<code>NULL</code>.</p>



<p>Initially, all next pointers are set to&nbsp;<code>NULL</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/02/15/117_sample.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,2,3,4,5,null,7]
<strong>Output:</strong> [1,#,2,3,#,4,5,7,#]
<strong>Explanation: </strong>Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
</pre>



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



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



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



<ul><li>The number of nodes in the tree is in the range&nbsp;<code>[0, 6000]</code>.</li><li><code>-100 &lt;= Node.val &lt;= 100</code></li></ul>



<p><strong>Follow-up:</strong></p>



<ul><li>You may only use constant extra space.</li><li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li></ul>



<h2><strong>Solution -2: Group nodes into levels</strong></h2>



<p>Use pre-order traversal to group nodes by levels.<br>Connects nodes in each level.</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:
  Node* connect(Node* root) {
    vector&lt;vector&lt;Node*&gt;&gt; levels;
    dfs(root, 0, levels);
    for (auto&amp; nodes : levels)
      for(int i = 0; i &lt; nodes.size() - 1; ++i)
        nodes[i]-&gt;next = nodes[i+1]; 
    return root;
  }
private:
  void dfs(Node *root, int d, vector&lt;vector&lt;Node*&gt;&gt;&amp; levels) {
    if (!root) return;
    if (levels.size() &lt; d+1) levels.push_back({});
    levels[d].push_back(root);
    dfs(root-&gt;left, d + 1, levels);
    dfs(root-&gt;right, d + 1, levels);
  }
};</pre>
</div></div>



<h2><strong>Solution -1: BFS level order traversal</strong></h2>



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



<p></p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  Node* connect(Node* root) {
    if (!root) return root;
    queue&lt;Node*&gt; q{{root}};
    while (!q.empty()) {
      int size = q.size();
      Node* p = nullptr;
      while (size--) {
        Node* t = q.front(); q.pop();
        if (p) 
          p-&gt;next = t, p = p-&gt;next;
        else
          p = t;
        if (t-&gt;left) q.push(t-&gt;left);
        if (t-&gt;right) q.push(t-&gt;right);
      }
    }
    return root;
  }
};</pre>
</div></div>



<h2><strong>Solution 1: BFS w/o extra space</strong></h2>



<p>Populating the next level while traversing current level.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  Node* connect(Node* root) {
    Node* p = root;        
    while (p) {
      Node dummy;
      Node* c = &amp;dummy;
      while (p) {
        if (p-&gt;left)
          c-&gt;next = p-&gt;left, c = c-&gt;next;
        if (p-&gt;right)
          c-&gt;next = p-&gt;right, c = c-&gt;next;
        p = p-&gt;next;
      }
      p = dummy.next;
    }
    return root;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/">花花酱 LeetCode 117. Populating Next Right Pointers in Each Node II</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-117-populating-next-right-pointers-in-each-node-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 144. Binary Tree Preorder Traversal</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-144-binary-tree-preorder-traversal/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-144-binary-tree-preorder-traversal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 30 Jan 2020 01:34:46 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[iteration]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6165</guid>

					<description><![CDATA[<p>Given a binary tree, return the&#160;preorder&#160;traversal of its nodes&#8217; values. Example: Input:&#160;[1,null,2,3] 1 \ 2 / 3 Output:&#160;[1,2,3] Follow up:&#160;Recursive solution is trivial, could you&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-144-binary-tree-preorder-traversal/">花花酱 LeetCode 144. Binary Tree Preorder 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>Given a binary tree, return the&nbsp;<em>preorder</em>&nbsp;traversal of its nodes&#8217; values.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong>&nbsp;<code>[1,null,2,3]</code>
   1
    \
     2
    /
   3

<strong>Output:</strong>&nbsp;<code>[1,2,3]</code>
</pre>



<p><strong>Follow up:</strong>&nbsp;Recursive solution is trivial, could you do it iteratively?</p>



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



<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; preorderTraversal(TreeNode* root) {
    vector&lt;int&gt; ans;    
    function&lt;void(TreeNode*)&gt; preorder = [&amp;](TreeNode* n) {
      if (!n) return;
      ans.push_back(n-&gt;val);
      preorder(n-&gt;left);
      preorder(n-&gt;right);
    };
    preorder(root);
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Stack</strong></h2>



<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; preorderTraversal(TreeNode* root) {
    vector&lt;int&gt; ans;
    stack&lt;TreeNode*&gt; s;
    if (root) s.push(root);
    while (!s.empty()) {
      TreeNode* n = s.top();
      ans.push_back(n-&gt;val);
      s.pop();
      if (n-&gt;right) s.push(n-&gt;right);
      if (n-&gt;left) s.push(n-&gt;left);            
    }
    return ans;
  }</pre>
</div></div>


<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-144-binary-tree-preorder-traversal/">花花酱 LeetCode 144. Binary Tree Preorder 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-144-binary-tree-preorder-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1305. All Elements in Two Binary Search Trees</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1305-all-elements-in-two-binary-search-trees/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1305-all-elements-in-two-binary-search-trees/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Dec 2019 19:05:06 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[inorder]]></category>
		<category><![CDATA[mergesort]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6021</guid>

					<description><![CDATA[<p>Given two binary search trees&#160;root1&#160;and&#160;root2. Return a list containing&#160;all the integers&#160;from&#160;both trees&#160;sorted in&#160;ascending&#160;order. Example 1: Input: root1 = [2,1,4], root2 = [1,0,3] Output: [0,1,1,2,3,4] Example&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1305-all-elements-in-two-binary-search-trees/">花花酱 LeetCode 1305. All Elements in Two Binary Search Trees</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 1305. All Elements in Two Binary Search Trees - 刷题找工作 EP290" width="500" height="375" src="https://www.youtube.com/embed/2cbsWlAHlj4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given two binary search trees&nbsp;<code>root1</code>&nbsp;and&nbsp;<code>root2</code>.</p>



<p>Return a list containing&nbsp;<em>all the integers</em>&nbsp;from&nbsp;<em>both trees</em>&nbsp;sorted in&nbsp;<strong>ascending</strong>&nbsp;order.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/12/18/q2-e1.png" alt=""/></figure>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root1 = [0,-10,10], root2 = [5,1,7,0,2]
<strong>Output:</strong> [-10,0,0,1,2,5,7,10]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root1 = [], root2 = [5,1,7,0,2]
<strong>Output:</strong> [0,1,2,5,7]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root1 = [0,-10,10], root2 = []
<strong>Output:</strong> [-10,0,10]
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/12/18/q2-e5-.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root1 = [1,null,8], root2 = [8,1]
<strong>Output:</strong> [1,1,8,8]
</pre>



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



<ul><li>Each tree has at most&nbsp;<code>5000</code>&nbsp;nodes.</li><li>Each node&#8217;s value is between&nbsp;<code>[-10^5, 10^5]</code>.</li></ul>



<h2><strong>Solution: Inorder traversal + Merge Sort</strong></h2>



<p>Time complexity: O(t1 + t2)<br>Space complexity: O(t1 + t2)</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; getAllElements(TreeNode* root1, TreeNode* root2) {    
    function&lt;void(TreeNode*, vector&lt;int&gt;&amp;)&gt; inorder = [&amp;](TreeNode* root, vector&lt;int&gt;&amp; t) {
      if (!root) return;
      inorder(root-&gt;left, t);
      t.push_back(root-&gt;val);
      inorder(root-&gt;right, t);
    };
    vector&lt;int&gt; t1;
    vector&lt;int&gt; t2;
    inorder(root1, t1);
    inorder(root2, t2);
    vector&lt;int&gt; m;
    int i = 0;
    int j = 0;
    while (m.size() != t1.size() + t2.size()) {
      if (j == t2.size()) m.push_back(t1[i++]);
      else if (i == t1.size()) m.push_back(t2[j++]);
      else m.push_back(t1[i] &lt; t2[j] ? t1[i++] : t2[j++]);      
    }
    return m;
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; getAllElements(TreeNode* root1, TreeNode* root2) {    
    function&lt;void(TreeNode*, vector&lt;int&gt;&amp;)&gt; inorder = [&amp;](TreeNode* root, vector&lt;int&gt;&amp; t) {
      if (!root) return;
      inorder(root-&gt;left, t);
      t.push_back(root-&gt;val);
      inorder(root-&gt;right, t);
    };
    vector&lt;int&gt; t1;
    vector&lt;int&gt; t2;
    inorder(root1, t1);
    inorder(root2, t2);
    vector&lt;int&gt; m;
    std::merge(begin(t1), end(t1), begin(t2), end(t2), back_inserter(m));    
    return m;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1305-all-elements-in-two-binary-search-trees/">花花酱 LeetCode 1305. All Elements in Two Binary Search Trees</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-1305-all-elements-in-two-binary-search-trees/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 987. Vertical Order Traversal of a Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-987-vertical-order-traversal-of-a-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-987-vertical-order-traversal-of-a-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Feb 2019 07:19:39 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[traversal]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4772</guid>

					<description><![CDATA[<p>Given a binary tree, return the&#160;vertical order&#160;traversal of its nodes&#160;values. For each node at position&#160;(X, Y), its left and right children respectively&#160;will be at positions&#160;(X-1,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-987-vertical-order-traversal-of-a-binary-tree/">花花酱 LeetCode 987. Vertical Order Traversal 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[
<p>Given a binary tree, return the&nbsp;<em>vertical order</em>&nbsp;traversal of its nodes&nbsp;values.</p>



<p>For each node at position&nbsp;<code>(X, Y)</code>, its left and right children respectively&nbsp;will be at positions&nbsp;<code>(X-1, Y-1)</code>&nbsp;and&nbsp;<code>(X+1, Y-1)</code>.</p>



<p>Running a vertical line from&nbsp;<code>X = -infinity</code>&nbsp;to&nbsp;<code>X = +infinity</code>, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing&nbsp;<code>Y</code>&nbsp;coordinates).</p>



<p>If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.</p>



<p>Return an list&nbsp;of non-empty reports in order of&nbsp;<code>X</code>&nbsp;coordinate.&nbsp; Every report will have a list of values of nodes.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/01/31/1236_example_1.PNG" alt=""/></figure>



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>[3,9,20,null,null,15,7]
<strong>Output: </strong>[[9],[3,15],[20],[7]]
<strong>Explanation: </strong>
Without loss of generality, we can assume the root node is at position (0, 0):
Then, the node with value 9 occurs at position (-1, -1);
The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);
The node with value 20 occurs at position (1, -1);
The node with value 7 occurs at position (2, -2).
</pre>



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



<figure class="wp-block-image is-resized"><img src="https://assets.leetcode.com/uploads/2019/01/31/tree2.png" alt="" width="294" height="187"/></figure>



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>[1,2,3,4,5,6,7]
<strong>Output: </strong>[[4],[2],[1,5,6],[3],[7]]
<strong>Explanation: </strong>
The node with value 5 and the node with value 6 have the same position according to the given scheme.
However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.
</pre>



<p><strong>Note:</strong></p>



<ol><li>The tree will have between&nbsp;1&nbsp;and&nbsp;<code>1000</code>&nbsp;nodes.</li><li>Each node&#8217;s value will be between&nbsp;<code>0</code>&nbsp;and&nbsp;<code>1000</code>.</li></ol>



<h2><strong>Solution: Ordered Map+ Ordered Set</strong></h2>



<p>Time complexity: O(nlogn)<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, running time: 0 ms, 921.6 KB 
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; verticalTraversal(TreeNode* root) {
    if (!root) return {};
    int min_x = INT_MAX;
    int max_x = INT_MIN;
    map&lt;pair&lt;int, int&gt;, multiset&lt;int&gt;&gt; h; // {y, x} -&gt; {vals}
    traverse(root, 0, 0, h, min_x, max_x);
    vector&lt;vector&lt;int&gt;&gt; ans(max_x - min_x + 1);
    for (const auto&amp; m : h) {      
      int x = m.first.second - min_x;
      ans[x].insert(end(ans[x]), begin(m.second), end(m.second));
    }
    return ans;
  }
private:
  void traverse(TreeNode* root, int x, int y, 
                map&lt;pair&lt;int, int&gt;, multiset&lt;int&gt;&gt;&amp; h,
                int&amp; min_x,
                int&amp; max_x) {
    if (!root) return;
    min_x = min(min_x, x);
    max_x = max(max_x, x);    
    h[{y, x}].insert(root-&gt;val);
    traverse(root-&gt;left, x - 1, y + 1, h, min_x, max_x);
    traverse(root-&gt;right, x + 1, y + 1, h, min_x, max_x);
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua, 36 ms, 6.8 MB
class Solution:
  def verticalTraversal(self, root: 'TreeNode') -&gt; 'List[List[int]]':
    if not root: return []    
    vals = []
    def preorder(root, x, y):
      if not root: return
      vals.append((x, y, root.val))
      preorder(root.left, x - 1, y + 1)
      preorder(root.right, x + 1, y + 1)
    preorder(root, 0, 0)    
    ans = []
    last_x = -1000
    for x, y, val in sorted(vals):
      if x != last_x:
        ans.append([])
        last_x = x
      ans[-1].append(val)
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-987-vertical-order-traversal-of-a-binary-tree/">花花酱 LeetCode 987. Vertical Order Traversal 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-987-vertical-order-traversal-of-a-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 971. Flip Binary Tree To Match Preorder Traversal</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-971-flip-binary-tree-to-match-preorder-traversal/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-971-flip-binary-tree-to-match-preorder-traversal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 06 Jan 2019 04:53:57 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[swap]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4611</guid>

					<description><![CDATA[<p>Given a binary tree with&#160;N&#160;nodes, each node has a different value from&#160;{1, ..., N}. A node in this binary tree can be&#160;flipped&#160;by swapping the left&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-971-flip-binary-tree-to-match-preorder-traversal/">花花酱 LeetCode 971. Flip Binary Tree To Match Preorder 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>Given a binary tree with&nbsp;<code>N</code>&nbsp;nodes, each node has a different value from&nbsp;<code>{1, ..., N}</code>.</p>



<p>A node in this binary tree can be&nbsp;<em>flipped</em>&nbsp;by swapping the left child and the right child of that node.</p>



<p>Consider the sequence of&nbsp;<code>N</code>&nbsp;values reported by a preorder traversal starting from the root.&nbsp; Call such a sequence of&nbsp;<code>N</code>&nbsp;values the&nbsp;<em>voyage</em>&nbsp;of the tree.</p>



<p>(Recall that a&nbsp;<em>preorder traversal</em>&nbsp;of a node means we report the current node&#8217;s value, then preorder-traverse the left child, then preorder-traverse the right child.)</p>



<p>Our goal is to flip the&nbsp;<strong>least number</strong>&nbsp;of nodes in the tree so that the voyage of the tree matches the&nbsp;<code>voyage</code>we are given.</p>



<p>If we can do so, then return a&nbsp;list&nbsp;of the values of all nodes flipped.&nbsp; You may return the answer in any order.</p>



<p>If we cannot do so, then return the list&nbsp;<code>[-1]</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/01/02/1219-01.png" alt=""/></figure>



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



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" alt=""/></figure>



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



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/01/02/1219-02.png" alt=""/></figure>



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



<p><strong>Note:</strong></p>



<ol><li><code>1 &lt;= N &lt;= 100</code></li></ol>



<h2>Solution: Pre-order traversal</h2>



<p>if root-&gt;val != v[pos] return [-1]<br>if root-&gt;left?-&gt;val != v[pos + 1], swap the nodes</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  vector&lt;int&gt; flipMatchVoyage(TreeNode* root, vector&lt;int&gt;&amp; voyage) {
    vector&lt;int&gt; flips;
    int pos = 0;
    solve(root, voyage, pos, flips);
    return flips;
  }
private:
  void solve(TreeNode* root, const vector&lt;int&gt;&amp; voyage, int&amp; pos, vector&lt;int&gt;&amp; flips) {
    if (!root) return;
    if (root-&gt;val != voyage.at(pos)) {
      flips.clear();
      flips.push_back(-1);
      return;
    }
    if (root-&gt;left &amp;&amp; root-&gt;left-&gt;val != voyage.at(pos + 1)) {
      swap(root-&gt;left, root-&gt;right);
      flips.push_back(root-&gt;val);
    }
    ++pos;
    solve(root-&gt;left, voyage, pos, flips);
    solve(root-&gt;right, voyage, pos, flips);   
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua, 60 ms
class Solution:
  def flipMatchVoyage(self, root, voyage):
    self.pos = 0
    self.flips = []
    def solve(root):
      if not root: return      
      if root.val != voyage[self.pos]:
        self.flips = [-1]
        return
      if root.left and root.left.val != voyage[self.pos + 1]:
        root.left, root.right = root.right, root.left
        self.flips.append(root.val)
      self.pos += 1
      solve(root.left)
      solve(root.right)    
    solve(root)
    return self.flips</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-971-flip-binary-tree-to-match-preorder-traversal/">花花酱 LeetCode 971. Flip Binary Tree To Match Preorder 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-971-flip-binary-tree-to-match-preorder-traversal/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 513. Find Bottom Left Tree Value</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-513-find-bottom-left-tree-value/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-513-find-bottom-left-tree-value/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 06 Mar 2018 04:55:25 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[inorder]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1978</guid>

					<description><![CDATA[<p>题目大意：给你一棵树，返回左下角（最后一行最左面）的节点的值。 https://leetcode.com/problems/find-bottom-left-tree-value/description/ Problem: Given a binary tree, find the leftmost value in the last row of the tree. Example 1: [crayon-663c90f9bd9ac693575436/] Example 2:  [crayon-663c90f9bd9ad248656239/] Note: You&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-513-find-bottom-left-tree-value/">花花酱 LeetCode 513. Find Bottom Left Tree Value</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>题目大意：给你一棵树，返回左下角（最后一行最左面）的节点的值。</p>
<p><a href="https://leetcode.com/problems/find-bottom-left-tree-value/description/">https://leetcode.com/problems/find-bottom-left-tree-value/description/</a></p>
<p><strong>Problem:</strong></p>
<p>Given a binary tree, find the leftmost value in the last row of the tree.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input:

    2
   / \
  1   3

Output:
1</pre><p><b>Example 2: </b></p><pre class="crayon-plain-tag">Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7</pre><p><b>Note:</b> You may assume the tree (i.e., the given root node) is not <b>NULL</b>.</p>
<p><strong>Solution 1: Inorder traversal with depth info</strong></p>
<p>The first node visited in the deepest row is the answer.</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 12 ms
class Solution {
public:
  int findBottomLeftValue(TreeNode* root) {
    int max_row = -1;    
    int ans;
    dfs(root, 0, max_row, ans);
    return ans;
  }
private:
  void inorder(TreeNode* root, int row, int&amp; max_row, int&amp; ans) {
    if (root == nullptr) return;
    inorder(root-&gt;left, row + 1, max_row, ans);
    if (row &gt; max_row) {
      ans = root-&gt;val;
      max_row = row;      
    }
    inorder(root-&gt;right, row + 1, max_row, ans);
  }
};</pre><p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 92 ms
"""
class Solution:
  def inorder(self, root, row):
    if not root: return
    self.inorder(root.left, row + 1)
    if row &gt; self.max_row:
      self.max_row, self.ans = row, root.val
    self.inorder(root.right, row + 1)    
      
  def findBottomLeftValue(self, root):        
    self.ans, self.max_row = 0, -1
    self.inorder(root, 0)
    return self.ans</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-513-find-bottom-left-tree-value/">花花酱 LeetCode 513. Find Bottom Left Tree Value</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-513-find-bottom-left-tree-value/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-663c90f9bdbb8507721698/] 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>
		<item>
		<title>花花酱 LeetCode 102. Binary Tree Level Order Traversal</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 04 Sep 2017 07:53:41 +0000</pubDate>
				<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[traversal]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=69</guid>

					<description><![CDATA[<p>Given a binary tree, return the level order traversal of its nodes&#8217; values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], [crayon-663c90f9bdccb885637222/]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/">花花酱 LeetCode 102. Binary Tree Level Order 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/Tuij96VBdu8?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p>Given a binary tree, return the <i>level order</i> traversal of its nodes&#8217; values. (ie, from left to right, level by level).</p>
<p>For example:<br />
Given binary tree <code>[3,9,20,null,null,15,7]</code>,</p><pre class="crayon-plain-tag">3
   / \
  9  20
    /  \
   15   7</pre><p>return its level order traversal as:</p><pre class="crayon-plain-tag">[
  [3],
  [9,20],
  [15,7]
]</pre><p>Solution 1: BFS O(n)</p><pre class="crayon-plain-tag">class Solution {
public:
    vector&lt;vector&lt;int&gt;&gt; levelOrder(TreeNode* root) {
        if(!root) return {};
        vector&lt;vector&lt;int&gt;&gt; ans;
        vector&lt;TreeNode*&gt; curr,next;
        curr.push_back(root);
        while(!curr.empty()) {
            ans.push_back({});
            for(TreeNode* node : curr) {
                ans.back().push_back(node-&gt;val);
                if(node-&gt;left) next.push_back(node-&gt;left);
                if(node-&gt;right) next.push_back(node-&gt;right);
            }
            curr.swap(next);
            next.clear();
        }
        return ans;
    }
};</pre><p>Solution 2: DFS O(n)</p><pre class="crayon-plain-tag">class Solution {
public:
    vector&lt;vector&lt;int&gt;&gt; levelOrder(TreeNode* root) {
        vector&lt;vector&lt;int&gt;&gt; ans;
        DFS(root, 0 /* depth */, ans);
        return ans;
    }
private:
    void DFS(TreeNode* root, int depth, vector&lt;vector&lt;int&gt;&gt;&amp; ans) {
        if(!root) return;
        // Works with pre/in/post order
        while(ans.size()&lt;=depth) ans.push_back({});
        ans[depth].push_back(root-&gt;val); // pre-order
        DFS(root-&gt;left, depth+1, ans);        
        DFS(root-&gt;right, depth+1, ans);   
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/">花花酱 LeetCode 102. Binary Tree Level Order 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/leetcode/leetcode-102-binary-tree-level-order-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
