<?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>BST Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/bst/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/bst/</link>
	<description></description>
	<lastBuildDate>Wed, 23 Nov 2022 08:40:42 +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>BST Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/bst/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2476. Closest Nodes Queries in a Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 22 Nov 2022 00:28:58 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[lower_bound]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<category><![CDATA[upper_bound]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9889</guid>

					<description><![CDATA[<p>You are given the&#160;root&#160;of a&#160;binary search tree&#160;and an array&#160;queries&#160;of size&#160;n&#160;consisting of positive integers. Find a&#160;2D&#160;array&#160;answer&#160;of size&#160;n&#160;where&#160;answer[i] = [mini, maxi]: mini&#160;is the&#160;largest&#160;value in the tree that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/">花花酱 LeetCode 2476. Closest Nodes Queries in a Binary Search 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[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 2476. Closest Nodes Queries in a Binary Search Tree - 刷题找工作 EP405" width="500" height="281" src="https://www.youtube.com/embed/UZYgQLMyocw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given the&nbsp;<code>root</code>&nbsp;of a&nbsp;<strong>binary search tree&nbsp;</strong>and an array&nbsp;<code>queries</code>&nbsp;of size&nbsp;<code>n</code>&nbsp;consisting of positive integers.</p>



<p>Find a&nbsp;<strong>2D</strong>&nbsp;array&nbsp;<code>answer</code>&nbsp;of size&nbsp;<code>n</code>&nbsp;where&nbsp;<code>answer[i] = [min<sub>i</sub>, max<sub>i</sub>]</code>:</p>



<ul><li><code>min<sub>i</sub></code>&nbsp;is the&nbsp;<strong>largest</strong>&nbsp;value in the tree that is smaller than or equal to&nbsp;<code>queries[i]</code>. If a such value does not exist, add&nbsp;<code>-1</code>&nbsp;instead.</li><li><code>max<sub>i</sub></code>&nbsp;is the&nbsp;<strong>smallest</strong>&nbsp;value in the tree that is greater than or equal to&nbsp;<code>queries[i]</code>. If a such value does not exist, add&nbsp;<code>-1</code>&nbsp;instead.</li></ul>



<p>Return&nbsp;<em>the array</em>&nbsp;<code>answer</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/09/28/bstreeedrawioo.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16]
<strong>Output:</strong> [[2,2],[4,6],[15,-1]]
<strong>Explanation:</strong> We answer the queries in the following way:
- The largest number that is smaller or equal than 2 in the tree is 2, and the smallest number that is greater or equal than 2 is still 2. So the answer for the first query is [2,2].
- The largest number that is smaller or equal than 5 in the tree is 4, and the smallest number that is greater or equal than 5 is 6. So the answer for the second query is [4,6].
- The largest number that is smaller or equal than 16 in the tree is 15, and the smallest number that is greater or equal than 16 does not exist. So the answer for the third query is [15,-1].
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/09/28/bstttreee.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [4,null,9], queries = [3]
<strong>Output:</strong> [[-1,4]]
<strong>Explanation:</strong> The largest number that is smaller or equal to 3 in the tree does not exist, and the smallest number that is greater or equal to 3 is 4. So the answer for the query is [-1,4].
</pre>



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



<ul><li>The number of nodes in the tree is in the range&nbsp;<code>[2, 10<sup>5</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 10<sup>6</sup></code></li><li><code>n == queries.length</code></li><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= queries[i] &lt;= 10<sup>6</sup></code></li></ul>



<h2><strong>Solution: Convert to sorted array</strong></h2>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1.png" alt="" class="wp-image-9898" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2.png" alt="" class="wp-image-9899" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3.png" alt="" class="wp-image-9900" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4.png" alt="" class="wp-image-9901" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Since we don&#8217;t know whether the tree is balanced or not, the safest and easiest way is to convert the tree into a sorted array using inorder traversal. Or just any traversal and sort the array later on.</p>



<p>Once we have a sorted array, we can use lower_bound / upper_bound to query.</p>



<p>Time complexity: O(qlogn)<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;vector&lt;int&gt;&gt; closestNodes(TreeNode* root, vector&lt;int&gt;&amp; queries) {    
    vector&lt;int&gt; vals;
    function&lt;void(TreeNode*)&gt; inorder = [&amp;](TreeNode* root) {
      if (!root) return;
      inorder(root-&gt;left);
      vals.push_back(root-&gt;val);
      inorder(root-&gt;right);
    };
    
    inorder(root);
    
    vector&lt;vector&lt;int&gt;&gt; ans;
    for (const int q : queries) {
      vector&lt;int&gt; cur{-1, -1};
      auto lit = upper_bound(begin(vals), end(vals), q);
      if (lit != begin(vals))
        cur[0] = *(prev(lit));
      auto rit = lower_bound(begin(vals), end(vals), q);
      if (rit != end(vals))
        cur[1] = *rit;      
      ans.push_back(std::move(cur));
    }
    return ans;
  }
};</pre>
</div></div>



<p>One binary search per query.</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;vector&lt;int&gt;&gt; closestNodes(TreeNode* root, vector&lt;int&gt;&amp; queries) {    
    vector&lt;int&gt; vals;
    function&lt;void(TreeNode*)&gt; inorder = [&amp;](TreeNode* root) {
      if (!root) return;
      inorder(root-&gt;left);
      if (vals.empty() || root-&gt;val &gt; vals.back()) vals.push_back(root-&gt;val);
      inorder(root-&gt;right);
    };
    
    inorder(root);
    
    vector&lt;vector&lt;int&gt;&gt; ans;
    for (const int q : queries) {
      vector&lt;int&gt; cur{-1, -1};      
      auto it = lower_bound(begin(vals), end(vals), q);
      if (it != end(vals) &amp;&amp; *it == q)
        cur[0] = cur[1] = q;
      else {
        if (it != begin(vals)) cur[0] = *prev(it);
        if (it != end(vals)) cur[1] = *it;        
      }
      ans.push_back(std::move(cur));
    }
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/">花花酱 LeetCode 2476. Closest Nodes Queries in a Binary Search 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/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 109. Convert Sorted List to Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-109-convert-sorted-list-to-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-109-convert-sorted-list-to-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 03:51:03 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8825</guid>

					<description><![CDATA[<p>Given the&#160;head&#160;of a singly linked list where elements are&#160;sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-109-convert-sorted-list-to-binary-search-tree/">花花酱 LeetCode 109. Convert Sorted List to Binary Search 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 the&nbsp;<code>head</code>&nbsp;of a singly linked list where elements are&nbsp;<strong>sorted in ascending order</strong>, convert it to a height balanced BST.</p>



<p>For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of&nbsp;<em>every</em>&nbsp;node never differ by more than 1.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/08/17/linked.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [-10,-3,0,5,9]
<strong>Output:</strong> [0,-3,9,-10,null,5]
<strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
</pre>



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



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



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



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



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



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



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



<ul><li>The number of nodes in&nbsp;<code>head</code>&nbsp;is in the range&nbsp;<code>[0, 2 * 10<sup>4</sup>]</code>.</li><li><code>-10<sup>5</sup>&nbsp;&lt;= Node.val &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution 1: Recursion w/ Fast + Slow Pointers</strong></h2>



<p>For each sublist, use fast/slow pointers to find the mid and build the tree.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  TreeNode *sortedListToBST(ListNode *head) {
    function&lt;TreeNode*(ListNode*, ListNode*)&gt; build 
      = [&amp;](ListNode* head, ListNode* tail) -&gt; TreeNode* {
      if (!head || head == tail) return nullptr;
      ListNode *fast = head, *slow = head;
      while (fast != tail &amp;&amp; fast-&gt;next != tail) {
        slow = slow-&gt;next;
        fast = fast-&gt;next-&gt;next;
      }
      TreeNode *root = new TreeNode(slow-&gt;val);
      root-&gt;left = build(head, slow);
      root-&gt;right = build(slow-&gt;next, tail);
      return root;
    };
    return build(head, nullptr);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-109-convert-sorted-list-to-binary-search-tree/">花花酱 LeetCode 109. Convert Sorted List to Binary Search 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/list/leetcode-109-convert-sorted-list-to-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1382. Balance a Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1382-balance-a-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1382-balance-a-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Mar 2020 08:39:29 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[balanced]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6500</guid>

					<description><![CDATA[<p>Given a binary search tree, return a&#160;balanced&#160;binary search tree with the same node values. A binary search tree is&#160;balanced&#160;if and only if&#160;the depth of the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1382-balance-a-binary-search-tree/">花花酱 LeetCode 1382. Balance a Binary Search 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[
<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 1382. Balance a Binary Search Tree - 刷题找工作 EP315" width="500" height="375" src="https://www.youtube.com/embed/U24USYuOWzw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given a binary search tree, return a&nbsp;<strong>balanced</strong>&nbsp;binary search tree with the same node values.</p>



<p>A binary search tree is&nbsp;<em>balanced</em>&nbsp;if and only if&nbsp;the depth of the two subtrees of&nbsp;every&nbsp;node never differ by more than 1.</p>



<p>If there is more than one answer, return any of them.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/08/22/1515_ex1.png" alt=""/></figure>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/08/22/1515_ex1_out.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,null,2,null,3,null,4,null,null]
<strong>Output:</strong> [2,1,3,null,null,null,4]
<strong>Explanation:</strong> This is not the only correct answer, [3,1,4,null,2,null,null] is also correct.
</pre>



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



<ul><li>The number of nodes in the tree is between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>10^4</code>.</li><li>The tree nodes will have distinct values between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>10^5</code>.</li></ul>



<h2><strong>Solution: Inorder + recursion</strong></h2>



<p>Use inorder traversal to collect a sorted array from BST. And then build a balanced BST from this sorted array in O(n) time.</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:
  TreeNode* balanceBST(TreeNode* root) {
    vector&lt;int&gt; vals;
    function&lt;void(TreeNode*)&gt; inorder = [&amp;](TreeNode* root) {
      if (!root) return;
      inorder(root-&gt;left);
      vals.push_back(root-&gt;val);
      inorder(root-&gt;right);
    };
    
    function&lt;TreeNode*(int, int)&gt; build = [&amp;](int l, int r) {
      if (l &gt; r) return (TreeNode*)nullptr;
      int m = l + (r - l) / 2;
      auto root = new TreeNode(vals[m]);
      root-&gt;left = build(l, m - 1);
      root-&gt;right = build(m + 1, r);
      return root;
    };
    
    inorder(root);
    return build(0, vals.size() - 1);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1382-balance-a-binary-search-tree/">花花酱 LeetCode 1382. Balance a Binary Search 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-1382-balance-a-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 108. Convert Sorted Array to Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 02 Feb 2020 18:54:12 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6244</guid>

					<description><![CDATA[<p>Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/">花花酱 LeetCode 108. Convert Sorted Array to Binary Search 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[
<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 108 Convert Sorted Array to Binary Search Tree - 刷题找工作 EP306" width="500" height="375" src="https://www.youtube.com/embed/O5BSAhg4n0M?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an array where elements are sorted in ascending order, convert it to a height balanced BST.</p>



<p>For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of&nbsp;<em>every</em>&nbsp;node never differ by more than 1.</p>



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



<pre class="wp-block-preformatted;crayon:false">Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5</pre>



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



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



<p>Recursively build a BST for a given range.</p>



<p>def build(nums, l, r):<br>  if l &gt; r: return None<br>  m = l + (r &#8211; l) / 2<br>  root = TreeNode(nums[m])<br>  root.left = build(nums, l, m &#8211; 1)<br>  root.right = build(nums, m + 1, r)<br>  return root<br><br>return build(nums, 0, len(nums) &#8211; 1)</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  TreeNode* sortedArrayToBST(vector&lt;int&gt;&amp; nums) {
    function&lt;TreeNode*(int l, int r)&gt; build = [&amp;](int l, int r) {
      if (l &gt; r) return static_cast&lt;TreeNode*&gt;(nullptr);      
      int m = l + (r - l) / 2;
      TreeNode* root = new TreeNode(nums[m]);
      root-&gt;left = build(l, m - 1);
      root-&gt;right = build(m + 1, r);
      return root;
    };
    return build(0, nums.size() - 1);
  }
};</pre>

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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  public TreeNode sortedArrayToBST(int[] nums) {
    return buildBST(nums, 0, nums.length - 1);
  }
  
  private TreeNode buildBST(int[] nums, int l, int r) {
    if (l &gt; r) return null;
    int m = l + (r - l) / 2;
    TreeNode root = new TreeNode(nums[m]);
    root.left = buildBST(nums, l, m - 1);
    root.right = buildBST(nums, m + 1, r);
    return root;
  }
}</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def sortedArrayToBST(self, nums: List[int]) -&gt; TreeNode:
    def buildBST(l: int, r: int) -&gt; TreeNode:
      if l &gt; r: return None
      m = l + (r - l) // 2
      root = TreeNode(nums[m])
      root.left = buildBST(l, m - 1)
      root.right = buildBST(m + 1, r)
      return root
    return buildBST(0, len(nums) - 1)</pre>

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

<pre class="crayon-plain-tag">// Author: Huahua
var sortedArrayToBST = function(nums) {
  var buildBST = function(l, r) {    
    if (l &gt; r) return null;
    let m = l + Math.floor((r - l) / 2);
    let root = new TreeNode(nums[m]);
    root.left = buildBST(l, m - 1);
    root.right = buildBST(m + 1, r);
    return root;
  }
  return buildBST(0, nums.length - 1);
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/">花花酱 LeetCode 108. Convert Sorted Array to Binary Search 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-108-convert-sorted-array-to-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 235. Lowest Common Ancestor of a Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-235-lowest-common-ancestor-of-a-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-235-lowest-common-ancestor-of-a-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 30 Jan 2020 03:31:48 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6174</guid>

					<description><![CDATA[<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the&#160;definition of LCA on&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-235-lowest-common-ancestor-of-a-binary-search-tree/">花花酱 LeetCode 235. Lowest Common Ancestor of a Binary Search 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 search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.</p>



<p>According to the&nbsp;<a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank" rel="noreferrer noopener">definition of LCA on Wikipedia</a>: “The lowest common ancestor is defined between two nodes p and q&nbsp;as the lowest node in T that has both p and q&nbsp;as descendants (where we allow&nbsp;<strong>a node to be a descendant of itself</strong>).”</p>



<p>Given binary search tree:&nbsp; root =&nbsp;[6,2,8,0,4,7,9,null,null,3,5]</p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" alt=""/></figure>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
<strong>Output:</strong> 6
<strong>Explanation: </strong>The LCA of nodes <code>2</code> and <code>8</code> is <code>6</code>.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
<strong>Output:</strong> 2
<strong>Explanation: </strong>The LCA of nodes <code>2</code> and <code>4</code> is <code>2</code>, since a node can be a descendant of itself according to the LCA definition.
</pre>



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



<ul><li>All of the nodes&#8217; values will be unique.</li><li>p and q are different and both values will&nbsp;exist in the BST.</li></ul>



<h2><strong>Solution: 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:
  TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {    
    if (p-&gt;val &lt; root-&gt;val &amp;&amp; q-&gt;val &lt; root-&gt;val) 
      return lowestCommonAncestor(root-&gt;left, p, q);
    if (p-&gt;val &gt; root-&gt;val &amp;&amp; q-&gt;val &gt; root-&gt;val)
      return lowestCommonAncestor(root-&gt;right, p, q);
    return root;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-235-lowest-common-ancestor-of-a-binary-search-tree/">花花酱 LeetCode 235. Lowest Common Ancestor of a Binary Search 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-235-lowest-common-ancestor-of-a-binary-search-tree/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 1296. Divide Array in Sets of K Consecutive Numbers</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1296-divide-array-in-sets-of-k-consecutive-numbers/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1296-divide-array-in-sets-of-k-consecutive-numbers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 27 Dec 2019 07:17:43 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5980</guid>

					<description><![CDATA[<p>Given an array of integers&#160;nums&#160;and a positive integer&#160;k, find whether it&#8217;s possible to divide this array into&#160;sets of&#160;k&#160;consecutive numbersReturn&#160;True&#160;if its possibleotherwise&#160;return&#160;False. Example 1: Input: nums&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1296-divide-array-in-sets-of-k-consecutive-numbers/">花花酱 LeetCode 1296. Divide Array in Sets of K Consecutive Numbers</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 1296. Divide Array in Sets of K Consecutive Numbers - 刷题找工作 EP287" width="500" height="375" src="https://www.youtube.com/embed/7W45U4WLtzg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an array of integers&nbsp;<code>nums</code>&nbsp;and a positive integer&nbsp;<code>k</code>, find whether it&#8217;s possible to divide this array into&nbsp;sets of&nbsp;<code>k</code>&nbsp;consecutive numbers<br>Return&nbsp;<code>True</code>&nbsp;if its possibleotherwise&nbsp;return&nbsp;<code>False</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,3,4,4,5,6], k = 4
<strong>Output:</strong> true
<strong>Explanation:</strong> Array can be divided into [1,2,3,4] and [3,4,5,6].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
<strong>Output:</strong> true
<strong>Explanation:</strong> Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
</pre>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4], k = 3
<strong>Output:</strong> false
<strong>Explanation:</strong> Each array should be divided in subarrays of size 3.
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10^5</code></li><li><code>1 &lt;= nums[i] &lt;= 10^9</code></li><li><code>1 &lt;= k &lt;= nums.length</code></li></ul>



<h2><strong>Solution: BST + Greedy</strong></h2>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1296-ep287-1.png" alt="" class="wp-image-5995" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1296-ep287-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1296-ep287-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1296-ep287-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Start from the smallest available number and find k consecutive numbers.</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="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool isPossibleDivide(vector&lt;int&gt;&amp; nums, int k) {
    if (nums.size() % k) return false;
    map&lt;int, int&gt; m;
    for (int num : nums) ++m[num];
    while (m.size()) {
      const int s = m.cbegin()-&gt;first;
      for (int i = 0; i &lt; k; ++i) {
        auto it = m.find(s + i);
        if (it == m.cend()) return false;
        if (--it-&gt;second == 0) m.erase(it);
      }
    }
    return true;
  }
};</pre>

</div><h2 class="tabtitle">C++/V2</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool isPossibleDivide(vector&lt;int&gt;&amp; nums, int k) {
    if (nums.size() % k) return false;
    map&lt;int, int&gt; m;
    for (int num : nums) ++m[num];
    while (m.size()) {
      auto it = m.begin();
      const int s = it-&gt;first;
      for (int i = 0; i &lt; k; ++i, ++it) {
        if (it-&gt;first != s + i) return false;
        if (--it-&gt;second == 0) m.erase(it);        
      }
    }
    return true;
  }
};</pre>
</div></div>



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



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1296-ep287-2.png" alt="" class="wp-image-5996" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1296-ep287-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1296-ep287-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1296-ep287-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<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">class Solution {
public:
  bool isPossibleDivide(vector&lt;int&gt;&amp; nums, int k) {
    if (nums.size() % k) return false;
    unordered_map&lt;int, int&gt; m;
    for (int num : nums) ++m[num];
    queue&lt;int&gt; starts;
    for (auto [n, f] : m)
      if (!m.count(n - 1)) starts.push(n);
    while (!starts.empty()) {
      int s = starts.front();
      starts.pop();
      for (int t = s + k - 1; t &gt;= s; t--) {
        if (m[t] &lt; m[s]) return false;
        if ((m[t] -= m[s]) == 0) {
          m.erase(t);
          if (m.count(t + 1)) starts.push(t + 1);
        }
      }
    }
    return true;
  }
};</pre>
</div></div>



<h2><strong>Related Problems</strong></h2>



<ul><li><a href="https://zxi.mytechroad.com/blog/hashtable/leetcode-128-longest-consecutive-sequence/">https://zxi.mytechroad.com/blog/hashtable/leetcode-128-longest-consecutive-sequence/</a></li></ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1296-divide-array-in-sets-of-k-consecutive-numbers/">花花酱 LeetCode 1296. Divide Array in Sets of K Consecutive Numbers</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/greedy/leetcode-1296-divide-array-in-sets-of-k-consecutive-numbers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 230. Kth Smallest Element in a BST</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-230-kth-smallest-element-in-a-bst/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-230-kth-smallest-element-in-a-bst/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 13 Apr 2019 07:36:05 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[kth]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5060</guid>

					<description><![CDATA[<p>Given a binary search tree, write a function&#160;kthSmallest&#160;to find the&#160;kth smallest element in it. Note:&#160;You may assume k is always valid, 1 ≤ k ≤&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-230-kth-smallest-element-in-a-bst/">花花酱 LeetCode 230. Kth Smallest Element in a BST</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 search tree, write a function&nbsp;<code>kthSmallest</code>&nbsp;to find the&nbsp;<strong>k</strong>th smallest element in it.</p>



<p><strong>Note:&nbsp;</strong><br>You may assume k is always valid, 1 ≤ k ≤ BST&#8217;s total elements.</p>



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



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



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



<pre class="wp-block-preformatted; crayon:false"><strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
<strong>Output:</strong> 3
</pre>



<p><strong>Follow up:</strong><br>What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?</p>



<p>Solution: Inorder traversal</p>



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



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

<pre class="crayon-plain-tag">class Solution {
public:
  int kthSmallest(TreeNode* root, int k) {
    return inorder(root, k);
  }
private:
  int inorder(TreeNode* root, int&amp; k) {
    if (!root) return -1;
    int x = inorder(root-&gt;left, k);
    if (k == 0) return x;
    if (--k == 0) return root-&gt;val;
    return inorder(root-&gt;right, k);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-230-kth-smallest-element-in-a-bst/">花花酱 LeetCode 230. Kth Smallest Element in a BST</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-230-kth-smallest-element-in-a-bst/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode Binary Trees 二叉树 SP12</title>
		<link>https://zxi.mytechroad.com/blog/sp/leetcode-binary-trees-sp12/</link>
					<comments>https://zxi.mytechroad.com/blog/sp/leetcode-binary-trees-sp12/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 16 Dec 2018 18:24:48 +0000</pubDate>
				<category><![CDATA[SP]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[sp]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4449</guid>

					<description><![CDATA[<p>Binary tree is one of the most frequently asked question type during interview. 二叉树是面试中经常会问到的问题。 The candidate needs to understand the recursively defined TreeNode and solve&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sp/leetcode-binary-trees-sp12/">花花酱 LeetCode Binary Trees 二叉树 SP12</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/PbGl8_-bZxI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></p>
<p>Binary tree is one of the most frequently asked question type during interview.</p>
<p>二叉树是面试中经常会问到的问题。</p>
<p>The candidate needs to understand the recursively defined TreeNode and solve the problem through recursion.</p>
<p>面试者需要理解递归定义的TreeNode数据类型，并且通过使用递归的方式来解决问题。</p>
<p>&nbsp;</p>
<p><img class="alignnone size-large wp-image-4450" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><br />
<img class="alignnone size-large wp-image-4451" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><br />
<img class="alignnone size-large wp-image-4452" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><br />
<img class="alignnone size-large wp-image-4453" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-4.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-4-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><br />
<img class="alignnone size-large wp-image-4454" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-5.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-5.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-5-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-5-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><br />
<img class="alignnone size-large wp-image-4455" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-6.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-6.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-6-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-6-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><br />
<img class="alignnone size-large wp-image-4456" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-7.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-7.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-7-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-7-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><br />
<img class="alignnone size-large wp-image-4457" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-8.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-8.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-8-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-8-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><br />
<img class="alignnone size-large wp-image-4458" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-9.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-9.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-9-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-9-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /><br />
<img class="alignnone size-large wp-image-4459" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-10.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-10.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-10-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/12/sp12-10-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sp/leetcode-binary-trees-sp12/">花花酱 LeetCode Binary Trees 二叉树 SP12</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/sp/leetcode-binary-trees-sp12/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 938. Range Sum of BST</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-938-range-sum-of-bst/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-938-range-sum-of-bst/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Nov 2018 07:41:47 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[inorder]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[range sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4285</guid>

					<description><![CDATA[<p>Problem Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-938-range-sum-of-bst/">花花酱 LeetCode 938. Range Sum of BST</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 the <code>root</code> node of a binary search tree, return the sum of values of all nodes with value between <code>L</code> and <code>R</code> (inclusive).</p>
<p>The binary search tree is guaranteed to have unique values.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>root = <span id="example-input-1-1">[10,5,15,3,7,null,18]</span>, L = <span id="example-input-1-2">7</span>, R = <span id="example-input-1-3">15</span>
<strong>Output: </strong><span id="example-output-1">32</span>
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>root = <span id="example-input-2-1">[10,5,15,3,7,13,18,1,null,6]</span>, L = <span id="example-input-2-2">6</span>, R = <span id="example-input-2-3">10</span>
<strong>Output: </strong><span id="example-output-2">23</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li>The number of nodes in the tree is at most <code>10000</code>.</li>
<li>The final answer is guaranteed to be less than <code>2^31</code>.</li>
</ol>
<h1>Solution: In-order traversal</h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, running time: 72 ms
class Solution {
public:
  int rangeSumBST(TreeNode* root, int L, int R) {
    if (!root) return 0;
    int sum = 0;
    if (root-&gt;val &gt;= L) sum += rangeSumBST(root-&gt;left, L, R);
    if (root-&gt;val &gt;= L &amp;&amp; root-&gt;val &lt;= R) sum += root-&gt;val;
    if (root-&gt;val &lt;= R) sum += rangeSumBST(root-&gt;right, L, R);
    return sum;
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-938-range-sum-of-bst/">花花酱 LeetCode 938. Range Sum of BST</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-938-range-sum-of-bst/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 915. Partition Array into Disjoint Intervals</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-915-partition-array-into-disjoint-intervals/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-915-partition-array-into-disjoint-intervals/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Sep 2018 14:57:56 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[Greedy]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[paritition]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4097</guid>

					<description><![CDATA[<p>Problem Given an array A, partition it into two (contiguous) subarrays left and right so that: Every element in left is less than or equal to every element in right. left and right are non-empty. left has the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-915-partition-array-into-disjoint-intervals/">花花酱 LeetCode 915. Partition Array into Disjoint Intervals</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 array <code>A</code>, partition it into two (contiguous) subarrays <code>left</code> and <code>right</code> so that:</p>
<ul>
<li>Every element in <code>left</code> is less than or equal to every element in <code>right</code>.</li>
<li><code>left</code> and <code>right</code> are non-empty.</li>
<li><code>left</code> has the smallest possible size.</li>
</ul>
<p>Return the <strong>length</strong> of <code>left</code> after such a partitioning.  It is guaranteed that such a partitioning exists.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">[5,0,3,8,6]</span>
<strong>Output: </strong><span id="example-output-1">3</span>
<strong>Explanation: </strong>left = [5,0,3], right = [8,6]
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre  class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">[1,1,1,0,6,12]</span>
<strong>Output: </strong><span id="example-output-2">4</span>
<strong>Explanation: </strong>left = [1,1,1,0], right = [6,12]
</pre>
</div>
<p><strong>Note:</strong></p>
<ol>
<li><code>2 &lt;= A.length &lt;= 30000</code></li>
<li><code>0 &lt;= A[i] &lt;= 10^6</code></li>
<li>It is guaranteed there is at least one way to partition <code>A</code> as described.</li>
</ol>
<h1><strong>Solution 1: BST</strong></h1>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 100 ms
class Solution {
public:
  int partitionDisjoint(vector&lt;int&gt;&amp; A) {
    multiset&lt;int&gt; s(begin(A) + 1, end(A));
    int left_max = A[0];
    for (int i = 1; i &lt; A.size(); ++i) {      
      if (*begin(s) &gt;= left_max) return i;
      s.erase(s.equal_range(A[i]).first);
      left_max = max(left_max, A[i]);      
    }
    return -1;
  }
};</pre><p></div></div></p>
<h1><strong>Solution 2: Greedy</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 28 ms
class Solution {
public:
  int partitionDisjoint(vector&lt;int&gt;&amp; A) {    
    int left_max = A[0];
    int cur_max = A[0];
    int left_len = 1;
    for (int i = 1; i &lt; A.size(); ++i) {
      if (A[i] &lt; left_max) {
        left_max = cur_max;
        left_len = i + 1;        
      } else {
        cur_max = max(cur_max, A[i]);
      }
    }
    return left_len;
  }
};</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-915-partition-array-into-disjoint-intervals/">花花酱 LeetCode 915. Partition Array into Disjoint Intervals</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/greedy/leetcode-915-partition-array-into-disjoint-intervals/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 855. Exam Room</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-855-exam-room/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-855-exam-room/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Jul 2018 21:28:53 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3374</guid>

					<description><![CDATA[<p>Problem In an exam room, there are N seats in a single row, numbered 0, 1, 2, ..., N-1. When a student enters the room, they must sit&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-855-exam-room/">花花酱 LeetCode 855. Exam Room</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>In an exam room, there are <code>N</code> seats in a single row, numbered <code>0, 1, 2, ..., N-1</code>.</p>
<p>When a student enters the room, they must sit in the seat that maximizes the distance to the closest person.  If there are multiple such seats, they sit in the seat with the lowest number.  (Also, if no one is in the room, then the student sits at seat number 0.)</p>
<p>Return a class <code>ExamRoom(int N)</code> that exposes two functions: <code>ExamRoom.seat()</code> returning an <code>int</code> representing what seat the student sat in, and <code>ExamRoom.leave(int p)</code> representing that the student in seat number <code>p</code> now leaves the room.  It is guaranteed that any calls to <code>ExamRoom.leave(p)</code> have a student sitting in seat <code>p</code>.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">["ExamRoom","seat","seat","seat","seat","leave","seat"]</span>, <span id="example-input-1-2">[[10],[],[],[],[],[4],[]]</span>
<strong>Output: </strong><span id="example-output-1">[null,0,9,4,2,null,5]</span>
<strong>Explanation</strong>:
ExamRoom(10) -&gt; null
seat() -&gt; 0, no one is in the room, then the student sits at seat number 0.
seat() -&gt; 9, the student sits at the last seat number 9.
seat() -&gt; 4, the student sits at the last seat number 4.
seat() -&gt; 2, the student sits at the last seat number 2.
leave(4) -&gt; null
seat() -&gt; 5, the student​​​​​​​ sits at the last seat number 5.
</pre>
<p>​​​​<strong>Note:</strong></p>
<ol>
<li><code>1 &lt;= N &lt;= 10^9</code></li>
<li><code>ExamRoom.seat()</code> and <code>ExamRoom.leave()</code> will be called at most <code>10^4</code> times across all test cases.</li>
<li>Calls to <code>ExamRoom.leave(p)</code> are guaranteed to have a student currently sitting in seat number <code>p</code>.</li>
</ol>
<h1><strong>Solution: BST</strong></h1>
<p>Use a BST (ordered set) to track the current seatings.</p>
<p>Time Complexity:</p>
<p>init: O(1)</p>
<p>seat: O(P)</p>
<p>leave: O(logP)</p>
<p>Space complexity: O(P)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 24 ms
class ExamRoom {
public:
  ExamRoom(int N): N_(N) {}

  int seat() {
    int p = 0;
    int max_dist = s_.empty() ? 0 : *s_.begin();
    auto left = s_.begin();    
    auto right = left;
    while (left != s_.end()) {
      ++right;
      int l = *left;
      int r = right != s_.end() ? *right : (2 * (N_ - 1) - *left);      
      int d = (r - l) / 2;      
      if (d &gt; max_dist) {
        max_dist = d;
        p = l + d;
      }
      left = right;
    }    
    s_.insert(p);
    return p;
  }

  void leave(int p) {
    s_.erase(p);
  }

private:
  const int N_;
  set&lt;int&gt; s_;
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-855-exam-room/">花花酱 LeetCode 855. Exam Room</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/simulation/leetcode-855-exam-room/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 701. Insert into a Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-701-insert-into-a-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-701-insert-into-a-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 13 Jul 2018 03:42:16 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[insert]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3099</guid>

					<description><![CDATA[<p>Problem Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-701-insert-into-a-binary-search-tree/">花花酱 LeetCode 701. Insert into a Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.</p>
<p>Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.</p>
<p>For example,</p><pre class="crayon-plain-tag">Given the tree:
        4
       / \
      2   7
     / \
    1   3
And the value to insert: 5</pre><p>You can return this binary search tree:</p><pre class="crayon-plain-tag">4
       /   \
      2     7
     / \   /
    1   3 5</pre><p>This tree is also valid:</p><pre class="crayon-plain-tag">5
       /   \
      2     7
     / \   
    1   3
         \
          4</pre><p></p>
<h1><strong>Solution: Recursion</strong></h1>
<p>Time complexity: O(logn ~ n)</p>
<p>Space complexity: O(logn ~ n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 52 ms
class Solution {
public:
  TreeNode* insertIntoBST(TreeNode* root, int val) {
    if (root == nullptr) return new TreeNode(val);
    if (val &gt; root-&gt;val)
      root-&gt;right = insertIntoBST(root-&gt;right, val);
    else
      root-&gt;left = insertIntoBST(root-&gt;left, val);
    return root;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-701-insert-into-a-binary-search-tree/">花花酱 LeetCode 701. Insert into a Binary Search 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-701-insert-into-a-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 703. Kth Largest Element in a Stream</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-703-kth-largest-element-in-a-stream/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-703-kth-largest-element-in-a-stream/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 13 Jul 2018 03:33:59 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[stream]]></category>
		<category><![CDATA[top k]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3095</guid>

					<description><![CDATA[<p>Problem Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-703-kth-largest-element-in-a-stream/">花花酱 LeetCode 703. Kth Largest Element in a Stream</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>Design a class to find the <strong>k</strong>th largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.</p>
<p>Your <code>KthLargest</code> class will have a constructor which accepts an integer <code>k</code> and an integer array <code>nums</code>, which contains initial elements from the stream. For each call to the method <code>KthLargest.add</code>, return the element representing the kth largest element in the stream.</p>
<p><strong>Example:</strong></p>
<pre class="crayon:false">int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3);   // returns 4
kthLargest.add(5);   // returns 5
kthLargest.add(10);  // returns 5
kthLargest.add(9);   // returns 8
kthLargest.add(4);   // returns 8
</pre>
<p><strong>Note: </strong><br />
You may assume that <code>nums</code>&#8216; length ≥ <code>k-1</code> and <code>k</code> ≥ 1.</p>
<h1><strong>Solution: BST / Min Heap</strong></h1>
<p>Time complexity: O(nlogk)</p>
<p>Space complexity: O(k)</p>
<p>C++ / BST</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 32 ms
class KthLargest {
public:
  KthLargest(int k, vector&lt;int&gt; nums): k_(k) {
    for (int num : nums)
      add(num);
  }

  int add(int val) {    
    s_.insert(val);
    if (s_.size() &gt; k_)
      s_.erase(s_.begin());
    return *s_.begin();
  }
private:
  const int k_;  
  multiset&lt;int&gt; s_;
};</pre><p>C++ / Min Heap</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms
class KthLargest {
public:
  KthLargest(int k, vector&lt;int&gt; nums): k_(k) {    
    for (int num : nums)
      add(num);
  }

  int add(int val) {    
    s_.push(val);
    if (s_.size() &gt; k_)
      s_.pop();
    return s_.top();
  }
private:
  const int k_;  
  priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt;&gt; s_; // min heap
};</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/heap/leetcode-703-kth-largest-element-in-a-stream/">花花酱 LeetCode 703. Kth Largest Element in a Stream</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/heap/leetcode-703-kth-largest-element-in-a-stream/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 700. Search in a Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-700-search-in-a-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-700-search-in-a-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 12 Jul 2018 15:24:50 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3092</guid>

					<description><![CDATA[<p>Problem Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-700-search-in-a-binary-search-tree/">花花酱 LeetCode 700. Search in a Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node&#8217;s value equals the given value. Return the subtree rooted with that node. If such node doesn&#8217;t exist, you should return NULL.</p>
<p>For example,</p>
<pre class="crayon:false">Given the tree:
        4
       / \
      2   7
     / \
    1   3

And the value to search: 2
</pre>
<p>You should return this subtree:</p>
<pre class="crayon:false">      2     
     / \   
    1   3
</pre>
<p>In the example above, if we want to search the value <code>5</code>, since there is no node with value <code>5</code>, we should return <code>NULL</code>.</p>
<h1>Solution: Recursion</h1>
<p>Time complexity: O(logn ~ n)</p>
<p>Space complexity: O(logn ~ n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 24 ms
class Solution {
public:
  TreeNode* searchBST(TreeNode* root, int val) {
    if (root == nullptr) return nullptr;
    if (val == root-&gt;val) 
      return root;
    else if (val &gt; root-&gt;val) 
      return searchBST(root-&gt;right, val);
    return searchBST(root-&gt;left, val);
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-700-search-in-a-binary-search-tree/">花花酱 LeetCode 700. Search in a Binary Search 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-700-search-in-a-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
