<?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>map &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/map/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Fri, 28 Mar 2025 03:46:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>map &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 3408. Design Task Manager</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-3408-design-task-manager/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-3408-design-task-manager/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 28 Mar 2025 03:45:03 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority queue]]></category>
		<category><![CDATA[treemap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10229</guid>

					<description><![CDATA[pq_ 使用std::map充当优先队列，存储(priority, taskId) -> userId m_ 使用std::unordered_map，存储taskId -> pq_的迭代器 所有操作都是O(logn) [crayon-67ef84e377ba8849755874/]]]></description>
										<content:encoded><![CDATA[
<ol class="wp-block-list"><li>pq_ 使用std::map充当优先队列，存储(priority, taskId) -> userId</li><li>m_ 使用std::unordered_map，存储taskId -> pq_的迭代器</li></ol>



<p>所有操作都是O(logn)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class TaskManager {
public:
    TaskManager(vector&lt;vector&lt;int&gt;&gt;&amp; tasks) {
      for (const auto&amp; task : tasks)
        add(task[0], task[1], task[2]);
    }

    void add(int userId, int taskId, int priority) {
      m_[taskId] = pq_.emplace(make_pair(priority, taskId), userId).first;
    }
    
    void edit(int taskId, int newPriority) {
      const int userId = m_[taskId]-&gt;second;
      rmv(taskId);
      add(userId, taskId, newPriority);
    }
    
    void rmv(int taskId) {
      auto it = m_.find(taskId);
      pq_.erase(it-&gt;second);
      m_.erase(it);
    }
    
    int execTop() {
      if (pq_.empty()) return -1;
      auto it = pq_.rbegin();
      const int userId = it-&gt;second;
      const int taskId = (it-&gt;first.second);
      rmv(taskId);
      return userId;
    }
  private:
    map&lt;std::pair&lt;int,int&gt;, int&gt; pq_; // (priority, taskId) -&gt; userId;
    unordered_map&lt;int, map&lt;std::pair&lt;int,int&gt;, int&gt;::iterator&gt; m_; // taskId -&gt; pq iterator
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/priority-queue/leetcode-3408-design-task-manager/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1418. Display Table of Food Orders in a Restaurant</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1418-display-table-of-food-orders-in-a-restaurant/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1418-display-table-of-food-orders-in-a-restaurant/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 20 Apr 2020 07:32:06 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[set]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6646</guid>

					<description><![CDATA[Given&#160;the array&#160;orders, which represents the orders that customers have done in a restaurant. More specifically&#160;orders[i]=[customerNamei,tableNumberi,foodItemi]&#160;where&#160;customerNamei&#160;is the name of the customer,&#160;tableNumberi&#160;is the table customer sit at,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given&nbsp;the array&nbsp;<code>orders</code>, which represents the orders that customers have done in a restaurant. More specifically&nbsp;<code>orders[i]=[customerName<sub>i</sub>,tableNumber<sub>i</sub>,foodItem<sub>i</sub>]</code>&nbsp;where&nbsp;<code>customerName<sub>i</sub></code>&nbsp;is the name of the customer,&nbsp;<code>tableNumber<sub>i</sub></code>&nbsp;is the table customer sit at, and&nbsp;<code>foodItem<sub>i</sub></code>&nbsp;is the item customer orders.</p>



<p><em>Return the restaurant&#8217;s “<strong>display table</strong>”</em>. The “<strong>display table</strong>” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
<strong>Output:</strong> [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] 
<strong>Explanation:
</strong>The displaying table looks like:
<strong>Table,Beef Burrito,Ceviche,Fried Chicken,Water</strong>
3    ,0           ,2      ,1            ,0
5    ,0           ,1      ,0            ,1
10   ,1           ,0      ,0            ,0
For the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".
For the table 5: Carla orders "Water" and "Ceviche".
For the table 10: Corina orders "Beef Burrito". 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]
<strong>Output:</strong> [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] 
<strong>Explanation:</strong> 
For the table 1: Adam and Brianna order "Canadian Waffles".
For the table 12: James, Ratesh and Amadeus order "Fried Chicken".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]
<strong>Output:</strong> [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;=&nbsp;orders.length &lt;= 5 * 10^4</code></li><li><code>orders[i].length == 3</code></li><li><code>1 &lt;= customerName<sub>i</sub>.length, foodItem<sub>i</sub>.length &lt;= 20</code></li><li><code>customerName<sub>i</sub></code>&nbsp;and&nbsp;<code>foodItem<sub>i</sub></code>&nbsp;consist of lowercase and uppercase English letters and the space character.</li><li><code>tableNumber<sub>i</sub>&nbsp;</code>is a valid integer between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>500</code>.</li></ul>



<p>Solution: TreeMap/Set + HashTable</p>



<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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;string&gt;&gt; displayTable(vector&lt;vector&lt;string&gt;&gt;&amp; orders) {
    map&lt;int, unordered_map&lt;string, int&gt;&gt; tables;
    set&lt;string&gt; foods;
    for (const auto&amp; order : orders) {
      ++tables[stoi(order[1])][order[2]];
      foods.insert(order[2]);
    }
    vector&lt;vector&lt;string&gt;&gt; ans;
    ans.push_back({{&quot;Table&quot;}});    
    ans.back().insert(end(ans.back()), begin(foods), end(foods));
    for (auto&amp; [table, m] : tables) {
      vector&lt;string&gt; line{to_string(table)};
      for (const auto&amp; food : foods)
        line.push_back(to_string(m[food]));
      ans.push_back(move(line));
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-1418-display-table-of-food-orders-in-a-restaurant/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 138. Copy List with Random Pointer</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-138-copy-list-with-random-pointer/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-138-copy-list-with-random-pointer/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 30 Jan 2020 04:12:20 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6178</guid>

					<description><![CDATA[A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.</p>



<p>Return a&nbsp;<a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank" rel="noreferrer noopener"><strong>deep copy</strong></a>&nbsp;of the list.</p>



<p>The Linked List is represented in the input/output as a list of&nbsp;<code>n</code>&nbsp;nodes. Each node is represented as a pair of&nbsp;<code>[val, random_index]</code>&nbsp;where:</p>



<ul class="wp-block-list"><li><code>val</code>: an integer representing&nbsp;<code>Node.val</code></li><li><code>random_index</code>: the index of the node (range from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n-1</code>) where random pointer points to, or&nbsp;<code>null</code>&nbsp;if it does not point to any node.</li></ul>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>



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



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



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = []
<strong>Output:</strong> []
<strong>Explanation:</strong> Given linked list is empty (null pointer), so return null.
</pre>



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



<ul class="wp-block-list"><li><code>-10000 &lt;= Node.val &lt;= 10000</code></li><li><code>Node.random</code>&nbsp;is null or pointing to a node in the linked list.</li><li>Number of Nodes will not exceed 1000.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Hashtable</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  Node* copyRandomList(Node* head) {
    if (!head) return head;

    unordered_map&lt;Node*, Node*&gt; m;    
    Node* cur = m[head] = new Node(head-&gt;val);
    Node* ans = cur;

    while (head) {
      if (head-&gt;random) {
        auto it = m.find(head-&gt;random);
        if (it == end(m))
          it = m.emplace(head-&gt;random, new Node(head-&gt;random-&gt;val)).first;
        cur-&gt;random = it-&gt;second;
      }

      if (head-&gt;next) {
        auto it = m.find(head-&gt;next);
        if (it == end(m))
          it = m.emplace(head-&gt;next, new Node(head-&gt;next-&gt;val)).first;        
        cur-&gt;next = it-&gt;second;
      }

      head = head-&gt;next;
      cur = cur-&gt;next;
    }
    
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-138-copy-list-with-random-pointer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1146. Snapshot Array</title>
		<link>https://zxi.mytechroad.com/blog/data-structure/leetcode-1146-snapshot-array/</link>
					<comments>https://zxi.mytechroad.com/blog/data-structure/leetcode-1146-snapshot-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 04 Aug 2019 17:52:50 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[map]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5388</guid>

					<description><![CDATA[Implement a SnapshotArray that supports the following interface: SnapshotArray(int length)&#160;initializes an array-like data structure with the given length.&#160;&#160;Initially, each element equals 0. void set(index, val)&#160;sets&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Implement a SnapshotArray that supports the following interface:</p>



<ul class="wp-block-list"><li><code>SnapshotArray(int length)</code>&nbsp;initializes an array-like data structure with the given length.&nbsp;&nbsp;<strong>Initially, each element equals 0</strong>.</li><li><code>void set(index, val)</code>&nbsp;sets the element at the given&nbsp;<code>index</code>&nbsp;to be equal to&nbsp;<code>val</code>.</li><li><code>int snap()</code>&nbsp;takes a snapshot of the array and returns the&nbsp;<code>snap_id</code>: the total number of times we called&nbsp;<code>snap()</code>&nbsp;minus&nbsp;<code>1</code>.</li><li><code>int get(index, snap_id)</code>&nbsp;returns the value at the given&nbsp;<code>index</code>, at the time we took the snapshot with the given&nbsp;<code>snap_id</code></li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> ["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]
<strong>Output:</strong> [null,null,0,null,5]
<strong>Explanation: </strong>
SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
snapshotArr.set(0,5);  // Set array[0] = 5
snapshotArr.snap();  // Take a snapshot, return snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0);  // Get the value of array[0] with snap_id = 0, return 5</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= length&nbsp;&lt;= 50000</code></li><li>At most&nbsp;<code>50000</code>&nbsp;calls will be made to&nbsp;<code>set</code>,&nbsp;<code>snap</code>, and&nbsp;<code>get</code>.</li><li><code>0 &lt;= index&nbsp;&lt;&nbsp;length</code></li><li><code>0 &lt;=&nbsp;snap_id &lt;&nbsp;</code>(the total number of times we call&nbsp;<code>snap()</code>)</li><li><code>0 &lt;=&nbsp;val &lt;= 10^9</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: map + upper_bound</strong></h2>



<p>Use a vector to store maps, one map per element.<br>The map stores {snap_id -> val}, use upper_bound to find the first version > snap_id and use previous version&#8217;s value.</p>



<p>Time complexity: <br>Set: O(log|snap_id|)<br>Get: O(log|snap_id|)  <br>Snap: O(1)<br>Space complexity: O(length + set_calls)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class SnapshotArray {
public:
  SnapshotArray(int length): id_(0), vals_(length) {}

  void set(int index, int val) {
    vals_[index][id_] = val;
  }

  int snap() { return id_++; }

  int get(int index, int snap_id) const {
    auto it = vals_[index].upper_bound(snap_id);
    if (it == begin(vals_[index])) return 0;
    return prev(it)-&gt;second;
  }
private:
  int id_;
  vector&lt;map&lt;int, int&gt;&gt; vals_;
};</pre>
</div></div>



<p><br></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/data-structure/leetcode-1146-snapshot-array/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[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;]]></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 decoding="async" 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 fetchpriority="high" decoding="async" 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 class="wp-block-list"><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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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="urvanov-syntax-highlighter-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>
]]></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>
	</channel>
</rss>
