<?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>tree &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/tree/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Sun, 13 Oct 2024 05:04:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>tree &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 3319. K-th Largest Perfect Subtree Size in Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Oct 2024 05:02:58 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[perfect tree]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10188</guid>

					<description><![CDATA[You are given the&#160;root&#160;of a&#160;binary tree&#160;and an integer&#160;k. Return an integer denoting the size of the&#160;kth&#160;largest&#160;perfect binary&#160; subtree, or&#160;-1&#160;if it doesn&#8217;t exist. A&#160;perfect binary tree&#160;is&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given the&nbsp;<code>root</code>&nbsp;of a&nbsp;<strong>binary tree</strong>&nbsp;and an integer&nbsp;<code>k</code>.</p>



<p>Return an integer denoting the size of the&nbsp;<code>k<sup>th</sup></code>&nbsp;<strong>largest<em>&nbsp;</em>perfect binary</strong><em>&nbsp;</em></p>



<p>subtree, or&nbsp;<code>-1</code>&nbsp;if it doesn&#8217;t exist.</p>



<p>A&nbsp;<strong>perfect binary tree</strong>&nbsp;is a tree where all leaves are on the same level, and every parent has two children.</p>



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



<p><strong>Input:</strong>&nbsp;root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</p>



<p><strong>Output:</strong>&nbsp;3</p>



<p><strong>Explanation:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2024/06/21/image.jpg" alt=""/></figure>



<p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in decreasing order are&nbsp;<code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br>The&nbsp;<code>2<sup>nd</sup></code>&nbsp;largest size is 3.</p>



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



<p><strong>Input:</strong>&nbsp;root = [1,2,3,4,5,6,7], k = 1</p>



<p><strong>Output:</strong>&nbsp;7</p>



<p><strong>Explanation:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2024/06/21/image1.jpg" alt=""/></figure>



<p>The sizes of the perfect binary subtrees in decreasing order are&nbsp;<code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p>



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



<p><strong>Input:</strong>&nbsp;root = [1,2,3,null,4], k = 3</p>



<p><strong>Output:</strong>&nbsp;-1</p>



<p><strong>Explanation:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2024/06/21/image4.jpg" alt=""/></figure>



<p>The sizes of the perfect binary subtrees in decreasing order are&nbsp;<code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p>



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



<ul class="wp-block-list"><li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li><li><code>1 &lt;= Node.val &lt;= 2000</code></li><li><code>1 &lt;= k &lt;= 1024</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: DFS</strong></h2>



<p>Write a function f() to return the perfect subtree size at node n.</p>



<p>def f(TreeNode n):<br>  if not n: return 0<br>  l, r = f(n.left), f(n.right)<br>  return l + r + 1 if l == r &amp;&amp; l != -1 else -1</p>



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



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int kthLargestPerfectSubtree(TreeNode* root, int k) {
    vector&amp;lt;int&gt; ss;
    function&amp;lt;int(TreeNode*)&gt; PerfectSubtree = &amp;#91;&amp;amp;](TreeNode* node) -&gt; int {
      if (node == nullptr) return 0;
      int l = PerfectSubtree(node-&gt;left);
      int r = PerfectSubtree(node-&gt;right);
      if (l == r &amp;amp;&amp;amp; l != -1) {
        ss.push_back(l + r + 1);
        return ss.back();
      }
      return -1;  
    };
    PerfectSubtree(root);
    sort(rbegin(ss), rend(ss));
    return k &amp;lt;= ss.size() ? ss&amp;#91;k - 1] : -1;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2583. Kth Largest Sum in a Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Mar 2023 15:51:10 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9973</guid>

					<description><![CDATA[You are given the&#160;root&#160;of a binary tree and a positive integer&#160;k. The&#160;level sum&#160;in the tree is the sum of the values of the nodes that&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given the&nbsp;<code>root</code>&nbsp;of a binary tree and a positive integer&nbsp;<code>k</code>.</p>



<p>The&nbsp;<strong>level sum</strong>&nbsp;in the tree is the sum of the values of the nodes that are on the&nbsp;<strong>same</strong>&nbsp;level.</p>



<p>Return<em>&nbsp;the&nbsp;</em><code>k<sup>th</sup></code><em>&nbsp;<strong>largest</strong>&nbsp;level sum in the tree (not necessarily distinct)</em>. If there are fewer than&nbsp;<code>k</code>&nbsp;levels in the tree, return&nbsp;<code>-1</code>.</p>



<p><strong>Note</strong>&nbsp;that two nodes are on the same level if they have the same distance from the root.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/12/14/binaryytreeedrawio-2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [5,8,9,2,1,3,7,4,6], k = 2
<strong>Output:</strong> 13
<strong>Explanation:</strong> The level sums are the following:
- Level 1: 5.
- Level 2: 8 + 9 = 17.
- Level 3: 2 + 1 + 3 + 7 = 13.
- Level 4: 4 + 6 = 10.
The 2<sup>nd</sup> largest level sum is 13.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/12/14/treedrawio-3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,2,null,3], k = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> The largest level sum is 3.
</pre>



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



<ul class="wp-block-list"><li>The number of nodes in the tree is&nbsp;<code>n</code>.</li><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= Node.val &lt;= 10<sup>6</sup></code></li><li><code>1 &lt;= k &lt;= n</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: DFS + Sorting</strong></h2>



<p>Use DFS to traverse the tree and accumulate level sum. Once done, sort the level sums and find the k-th largest one.</p>



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



<p>Note: sum can be very large, use long long.</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:
  long long kthLargestLevelSum(TreeNode* root, int k) {
    vector&lt;long long&gt; sums;
    function&lt;void(TreeNode*, int)&gt; dfs = [&amp;](TreeNode* root, int d) {
      if (!root) return;
      while (d &gt;= sums.size()) sums.push_back(0);
      sums[d] += root-&gt;val;
      dfs(root-&gt;left, d + 1);
      dfs(root-&gt;right, d + 1);
    };
    dfs(root, 0);
    if (sums.size() &lt; k) return -1;
    sort(rbegin(sums), rend(sums));
    return sums[k - 1];
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2477. Minimum Fuel Cost to Report to the Capital</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 26 Nov 2022 16:41:02 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9905</guid>

					<description><![CDATA[There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of&#160;n&#160;cities numbered from&#160;0&#160;to&#160;n - 1&#160;and exactly&#160;n - 1&#160;roads. The&#8230;]]></description>
										<content:encoded><![CDATA[
<p>There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of&nbsp;<code>n</code>&nbsp;cities numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;and exactly&nbsp;<code>n - 1</code>&nbsp;roads. The capital city is city&nbsp;<code>0</code>. You are given a 2D integer array&nbsp;<code>roads</code>&nbsp;where&nbsp;<code>roads[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>&nbsp;denotes that there exists a&nbsp;<strong>bidirectional road</strong>&nbsp;connecting cities&nbsp;<code>a<sub>i</sub></code>&nbsp;and&nbsp;<code>b<sub>i</sub></code>.</p>



<p>There is a meeting for the representatives of each city. The meeting is in the capital city.</p>



<p>There is a car in each city. You are given an integer&nbsp;<code>seats</code>&nbsp;that indicates the number of seats in each car.</p>



<p>A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.</p>



<p>Return&nbsp;<em>the minimum number of liters of fuel to reach the capital city</em>.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> roads = [[0,1],[0,2],[0,3]], seats = 5
<strong>Output:</strong> 3
<strong>Explanation:</strong> 
- Representative<sub>1</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>2</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>3</sub> goes directly to the capital with 1 liter of fuel.
It costs 3 liters of fuel at minimum. 
It can be proven that 3 is the minimum number of liters of fuel needed.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/11/16/2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2
<strong>Output:</strong> 7
<strong>Explanation:</strong> 
- Representative<sub>2</sub> goes directly to city 3 with 1 liter of fuel.
- Representative<sub>2</sub> and representative<sub>3</sub> go together to city 1 with 1 liter of fuel.
- Representative<sub>2</sub> and representative<sub>3</sub> go together to the capital with 1 liter of fuel.
- Representative<sub>1</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>5</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>6</sub> goes directly to city 4 with 1 liter of fuel.
- Representative<sub>4</sub> and representative<sub>6</sub> go together to the capital with 1 liter of fuel.
It costs 7 liters of fuel at minimum. 
It can be proven that 7 is the minimum number of liters of fuel needed.
</pre>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> roads = [], seats = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> No representatives need to travel to the capital city.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>roads.length == n - 1</code></li><li><code>roads[i].length == 2</code></li><li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub>&nbsp;&lt; n</code></li><li><code>a<sub>i</sub>&nbsp;!= b<sub>i</sub></code></li><li><code>roads</code>&nbsp;represents a valid tree.</li><li><code>1 &lt;= seats &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Greedy + DFS</strong></h2>



<p>To reach the minimum cost, we must share cars if possible, say X reps from children nodes to an intermediate node u on the way towards capital 0.  Then they all changes cars at node u, and we need (X + 1) // seats cars/fuel from u to 0.</p>



<p>We use DFS to count # of reps at each node u while accumulating the total cost.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  long long minimumFuelCost(vector&lt;vector&lt;int&gt;&gt;&amp; roads, int seats) {
    long long ans = 0;
    vector&lt;vector&lt;int&gt;&gt; g(roads.size() + 1);
    for (const vector&lt;int&gt;&amp; r : roads) {
      g[r[0]].push_back(r[1]);
      g[r[1]].push_back(r[0]);
    }
    // Returns total # of children of u.
    function&lt;int(int, int)&gt; dfs = [&amp;](int u, int p, int rep = 1) {      
      for (int v : g[u])
        if (v != p) rep += dfs(v, u);
      if (u) ans += (rep + seats - 1) / seats;
      return rep;
    };
    dfs(0, -1);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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[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;]]></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; web-share" referrerpolicy="strict-origin-when-cross-origin" 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 class="wp-block-list"><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 decoding="async" 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 decoding="async" 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 class="wp-block-list"><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 class="wp-block-heading"><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 fetchpriority="high" decoding="async" 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 decoding="async" 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 loading="lazy" decoding="async" 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="auto, (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 loading="lazy" decoding="async" 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="auto, (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="urvanov-syntax-highlighter-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="urvanov-syntax-highlighter-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>
]]></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 2265. Count Nodes Equal to Average of Subtree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2265-count-nodes-equal-to-average-of-subtree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2265-count-nodes-equal-to-average-of-subtree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 10 May 2022 07:12:15 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9728</guid>

					<description><![CDATA[Given the&#160;root&#160;of a binary tree, return&#160;the number of nodes where the value of the node is equal to the&#160;average&#160;of the values in its&#160;subtree. Note: The&#160;average&#160;of&#160;n&#160;elements&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the&nbsp;<code>root</code>&nbsp;of a binary tree, return&nbsp;<em>the number of nodes where the value of the node is equal to the&nbsp;<strong>average</strong>&nbsp;of the values in its&nbsp;<strong>subtree</strong></em>.</p>



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



<ul class="wp-block-list"><li>The&nbsp;<strong>average</strong>&nbsp;of&nbsp;<code>n</code>&nbsp;elements is the&nbsp;<strong>sum</strong>&nbsp;of the&nbsp;<code>n</code>&nbsp;elements divided by&nbsp;<code>n</code>&nbsp;and&nbsp;<strong>rounded down</strong>&nbsp;to the nearest integer.</li><li>A&nbsp;<strong>subtree</strong>&nbsp;of&nbsp;<code>root</code>&nbsp;is a tree consisting of&nbsp;<code>root</code>&nbsp;and all of its descendants.</li></ul>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/03/15/image-20220315203925-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [4,8,5,0,1,null,6]
<strong>Output:</strong> 5
<strong>Explanation:</strong> 
For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.
For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.
For the node with value 0: The average of its subtree is 0 / 1 = 0.
For the node with value 1: The average of its subtree is 1 / 1 = 1.
For the node with value 6: The average of its subtree is 6 / 1 = 6.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/03/26/image-20220326133920-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> For the node with value 1: The average of its subtree is 1 / 1 = 1.
</pre>



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



<ul class="wp-block-list"><li>The number of nodes in the tree is in the range&nbsp;<code>[1, 1000]</code>.</li><li><code>0 &lt;= Node.val &lt;= 1000</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Recursion</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int averageOfSubtree(TreeNode* root) {    
    // Returns {sum(val), sum(node), ans}
    function&lt;tuple&lt;int, int, int&gt;(TreeNode*)&gt; getSum 
      = [&amp;](TreeNode* root) -&gt; tuple&lt;int, int, int&gt; {
      if (!root) return {0, 0, 0};
      auto [lv, lc, la] = getSum(root-&gt;left);
      auto [rv, rc, ra] = getSum(root-&gt;right);
      int sum = lv + rv + root-&gt;val;
      int count = lc + rc + 1;
      int ans = la + ra + (root-&gt;val == sum / count);
      return {sum, count, ans};
    };    
    return get&lt;2&gt;(getSum(root));
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-2265-count-nodes-equal-to-average-of-subtree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2236. Root Equals Sum of Children</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2236-root-equals-sum-of-children/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2236-root-equals-sum-of-children/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 16 Apr 2022 15:09:51 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9647</guid>

					<description><![CDATA[You are given the&#160;root&#160;of a&#160;binary tree&#160;that consists of exactly&#160;3&#160;nodes: the root, its left child, and its right child. Return&#160;true&#160;if the value of the root is&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given the&nbsp;<code>root</code>&nbsp;of a&nbsp;<strong>binary tree</strong>&nbsp;that consists of exactly&nbsp;<code>3</code>&nbsp;nodes: the root, its left child, and its right child.</p>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if the value of the root is equal to the&nbsp;<strong>sum</strong>&nbsp;of the values of its two children, or&nbsp;</em><code>false</code><em>&nbsp;otherwise</em>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/04/08/graph3drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [10,4,6]
<strong>Output:</strong> true
<strong>Explanation:</strong> The values of the root, its left child, and its right child are 10, 4, and 6, respectively.
10 is equal to 4 + 6, so we return true.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/04/08/graph3drawio-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [5,3,1]
<strong>Output:</strong> false
<strong>Explanation:</strong> The values of the root, its left child, and its right child are 5, 3, and 1, respectively.
5 is not equal to 3 + 1, so we return false.
</pre>



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



<ul class="wp-block-list"><li>The tree consists only of the root, its left child, and its right child.</li><li><code>-100 &lt;= Node.val &lt;= 100</code></li></ul>



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



<p>Just want to check whether you know binary tree or not.</p>



<p>Time complexity: O(1)<br>Space complexity: O(1)</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:
  bool checkTree(TreeNode* root) {
    return root-&gt;val == root-&gt;left-&gt;val + root-&gt;right-&gt;val;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-2236-root-equals-sum-of-children/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2196. Create Binary Tree From Descriptions</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2196-create-binary-tree-from-descriptions/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2196-create-binary-tree-from-descriptions/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 08 Mar 2022 11:58:52 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9558</guid>

					<description><![CDATA[You are given a 2D integer array&#160;descriptions&#160;where&#160;descriptions[i] = [parenti, childi, isLefti]&#160;indicates that&#160;parenti&#160;is the&#160;parent&#160;of&#160;childi&#160;in a&#160;binary&#160;tree of&#160;unique&#160;values. Furthermore, If&#160;isLefti&#160;== 1, then&#160;childi&#160;is the left child of&#160;parenti. If&#160;isLefti&#160;== 0,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a 2D integer array&nbsp;<code>descriptions</code>&nbsp;where&nbsp;<code>descriptions[i] = [parent<sub>i</sub>, child<sub>i</sub>, isLeft<sub>i</sub>]</code>&nbsp;indicates that&nbsp;<code>parent<sub>i</sub></code>&nbsp;is the&nbsp;<strong>parent</strong>&nbsp;of&nbsp;<code>child<sub>i</sub></code>&nbsp;in a&nbsp;<strong>binary</strong>&nbsp;tree of&nbsp;<strong>unique</strong>&nbsp;values. Furthermore,</p>



<ul class="wp-block-list"><li>If&nbsp;<code>isLeft<sub>i</sub>&nbsp;== 1</code>, then&nbsp;<code>child<sub>i</sub></code>&nbsp;is the left child of&nbsp;<code>parent<sub>i</sub></code>.</li><li>If&nbsp;<code>isLeft<sub>i</sub>&nbsp;== 0</code>, then&nbsp;<code>child<sub>i</sub></code>&nbsp;is the right child of&nbsp;<code>parent<sub>i</sub></code>.</li></ul>



<p>Construct the binary tree described by&nbsp;<code>descriptions</code>&nbsp;and return&nbsp;<em>its&nbsp;<strong>root</strong></em>.</p>



<p>The test cases will be generated such that the binary tree is&nbsp;<strong>valid</strong>.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]
<strong>Output:</strong> [50,20,80,15,17,19]
<strong>Explanation:</strong> The root node is the node with value 50 since it has no parent.
The resulting binary tree is shown in the diagram.
</pre>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> descriptions = [[1,2,1],[2,3,0],[3,4,1]]
<strong>Output:</strong> [1,2,null,null,3,4]
<strong>Explanation:</strong> The root node is the node with value 1 since it has no parent.
The resulting binary tree is shown in the diagram.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= descriptions.length &lt;= 10<sup>4</sup></code></li><li><code>descriptions[i].length == 3</code></li><li><code>1 &lt;= parent<sub>i</sub>, child<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= isLeft<sub>i</sub>&nbsp;&lt;= 1</code></li><li>The binary tree described by&nbsp;<code>descriptions</code>&nbsp;is valid.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Hashtable + Recursion</strong></h2>



<ol class="wp-block-list"><li>Use one hashtable to track the children of each node.</li><li>Use another hashtable to track the parent of each node.</li><li>Find the root who doesn&#8217;t have parent.</li><li>Build the tree recursively from root.<br></li></ol>



<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:
  TreeNode* createBinaryTree(vector&lt;vector&lt;int&gt;&gt;&amp; descriptions) {
    unordered_set&lt;int&gt; hasParent;
    unordered_map&lt;int, pair&lt;int, int&gt;&gt; children;
    for (const auto&amp; d : descriptions) {
      hasParent.insert(d[1]);
      (d[2] ? children[d[0]].first : children[d[0]].second) = d[1];      
    }
    int root = -1;
    for (const auto&amp; d : descriptions)
      if (!hasParent.count(d[0])) root = d[0];
    function&lt;TreeNode*(int)&gt; build = [&amp;](int cur) -&gt; TreeNode* {      
      if (!cur) return nullptr;
      return new TreeNode(cur, 
                          build(children[cur].first),
                          build(children[cur].second));
    };  
    return build(root);
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-2196-create-binary-tree-from-descriptions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 222. Count Complete Tree Nodes</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-222-count-complete-tree-nodes/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-222-count-complete-tree-nodes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 08 Dec 2021 04:44:30 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9065</guid>

					<description><![CDATA[Given the&#160;root&#160;of a&#160;complete&#160;binary tree, return the number of the nodes in the tree. According to&#160;Wikipedia, every level, except possibly the last, is completely filled in&#8230;]]></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 loading="lazy" title="花花酱 LeetCode 222. Count Complete Tree Nodes - 刷题找工作 EP395" width="500" height="281" src="https://www.youtube.com/embed/dtLIe1rHYPg?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Given the&nbsp;<code>root</code>&nbsp;of a&nbsp;<strong>complete</strong>&nbsp;binary tree, return the number of the nodes in the tree.</p>



<p>According to&nbsp;<strong><a href="http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees" target="_blank" rel="noreferrer noopener">Wikipedia</a></strong>, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>2<sup>h</sup></code>&nbsp;nodes inclusive at the last level&nbsp;<code>h</code>.</p>



<p>Design an algorithm that runs in less than&nbsp;<code>O(n)</code>&nbsp;time complexity.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/01/14/complete.jpg" alt=""/></figure>



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



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



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



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



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



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



<ul class="wp-block-list"><li>The number of nodes in the tree is in the range&nbsp;<code>[0, 5 * 10<sup>4</sup>]</code>.</li><li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li><li>The tree is guaranteed to be&nbsp;<strong>complete</strong>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Recursion</strong></h2>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-1.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-1.png" alt="" class="wp-image-9118" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-1-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-2.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-2.png" alt="" class="wp-image-9119" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-2-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-3.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-3.png" alt="" class="wp-image-9120" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-3-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-4.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-4.png" alt="" class="wp-image-9121" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-4-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-5.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-5.png" alt="" class="wp-image-9122" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-5.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-5-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-5-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-56.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-56.png" alt="" class="wp-image-9123" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-56.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-56-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/222-ep395-56-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>





<p><br>For each node, count the height of it&#8217;s left and right subtree by going left only.</p>



<p>Let L = height(left) R = height(root),  if L == R, which means the left subtree is perfect.<br>It has (2^L &#8211; 1) nodes, +1 root, we only need to count nodes of right subtree recursively.<br>If L != R, L must be R + 1 since the tree is complete, which means the right subtree is perfect.<br>It has (2^(L-1) &#8211; 1) nodes, +1 root, we only need to count nodes of left subtree recursively.</p>



<p>Time complexity: T(n) = T(n/2) + O(logn) = O(logn*logn)</p>



<p>Space complexity: O(logn)</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:
  int countNodes(TreeNode* root) {
    if (root == nullptr) return 0;
    int l = depth(root-&gt;left);
    int r = depth(root-&gt;right);
    if (l == r) 
      return (1 &lt;&lt; l) + countNodes(root-&gt;right);
    else
      return (1 &lt;&lt; (l - 1)) + countNodes(root-&gt;left);
  }
private:
  int depth(TreeNode* root) {
    if (root == nullptr) return 0;
    return 1 + depth(root-&gt;left);
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-222-count-complete-tree-nodes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2096-step-by-step-directions-from-a-binary-tree-node-to-another/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2096-step-by-step-directions-from-a-binary-tree-node-to-another/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Dec 2021 08:11:36 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[LCA]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[shortest path]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9023</guid>

					<description><![CDATA[You are given the&#160;root&#160;of a&#160;binary tree&#160;with&#160;n&#160;nodes. Each node is uniquely assigned a value from&#160;1&#160;to&#160;n. You are also given an integer&#160;startValue&#160;representing the value of the start&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given the&nbsp;<code>root</code>&nbsp;of a&nbsp;<strong>binary tree</strong>&nbsp;with&nbsp;<code>n</code>&nbsp;nodes. Each node is uniquely assigned a value from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>. You are also given an integer&nbsp;<code>startValue</code>&nbsp;representing the value of the start node&nbsp;<code>s</code>, and a different integer&nbsp;<code>destValue</code>&nbsp;representing the value of the destination node&nbsp;<code>t</code>.</p>



<p>Find the&nbsp;<strong>shortest path</strong>&nbsp;starting from node&nbsp;<code>s</code>&nbsp;and ending at node&nbsp;<code>t</code>. Generate step-by-step directions of such path as a string consisting of only the&nbsp;<strong>uppercase</strong>&nbsp;letters&nbsp;<code>'L'</code>,&nbsp;<code>'R'</code>, and&nbsp;<code>'U'</code>. Each letter indicates a specific direction:</p>



<ul class="wp-block-list"><li><code>'L'</code>&nbsp;means to go from a node to its&nbsp;<strong>left child</strong>&nbsp;node.</li><li><code>'R'</code>&nbsp;means to go from a node to its&nbsp;<strong>right child</strong>&nbsp;node.</li><li><code>'U'</code>&nbsp;means to go from a node to its&nbsp;<strong>parent</strong>&nbsp;node.</li></ul>



<p>Return&nbsp;<em>the step-by-step directions of the&nbsp;<strong>shortest path</strong>&nbsp;from node&nbsp;</em><code>s</code><em>&nbsp;to node</em>&nbsp;<code>t</code>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/15/eg1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
<strong>Output:</strong> "UURL"
<strong>Explanation:</strong> The shortest path is: 3 → 1 → 5 → 2 → 6.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/15/eg2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [2,1], startValue = 2, destValue = 1
<strong>Output:</strong> "L"
<strong>Explanation:</strong> The shortest path is: 2 → 1.
</pre>



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



<ul class="wp-block-list"><li>The number of nodes in the tree is&nbsp;<code>n</code>.</li><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= Node.val &lt;= n</code></li><li>All the values in the tree are&nbsp;<strong>unique</strong>.</li><li><code>1 &lt;= startValue, destValue &lt;= n</code></li><li><code>startValue != destValue</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Lowest common ancestor</strong></h2>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/2096-ex1.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/2096-ex1.png" alt="" class="wp-image-9028" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/2096-ex1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/2096-ex1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/12/2096-ex1-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<p>It&#8217;s no hard to see that the shortest path is from the start node to the lowest common ancestor (LCA) of (start, end), then to the end node. The key is to find the LCA while finding paths from root to two nodes.</p>



<p>We can use recursion to find/build a path from root to a target node.<br>The common prefix of these two paths is the path from root to the LCA that we need to remove from the shortest path.<br>e.g. <br>root to start &#8220;LLRLR&#8221;<br>root to dest &#8220;LLLR&#8221;<br>common prefix is &#8220;LL&#8221;, after removing, it becomes:<br>LCA to start &#8220;RLR&#8221;<br>LCA to dest &#8220;LR&#8221;<br>Final path becomes &#8220;UUU&#8221; + &#8220;LR&#8221; = &#8220;UUULR&#8221;</p>



<p>The final step is to replace the L/R with U for the start path since we are moving up and then concatenate with the target path.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  string getDirections(TreeNode* root, int startValue, int destValue) {
    string startPath;
    string destPath;
    buildPath(root, startValue, startPath);
    buildPath(root, destValue, destPath);    
    // Remove common suffix (shared path from root to LCA)
    while (!startPath.empty() &amp;&amp; !destPath.empty() 
           &amp;&amp; startPath.back() == destPath.back()) {
      startPath.pop_back();
      destPath.pop_back();
    }
    reverse(begin(destPath), end(destPath));
    return string(startPath.size(), 'U') + destPath;
  }
private:
  bool buildPath(TreeNode* root, int t, string&amp; path) {
    if (!root) return false;
    if (root-&gt;val == t) return true;
    if (buildPath(root-&gt;left, t, path)) {
      path.push_back('L');
      return true;
    } else if (buildPath(root-&gt;right, t, path)) {
      path.push_back('R');
      return true;
    }
    return false;
  }
};</pre>
</div></div>



<p><br>  </p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-2096-step-by-step-directions-from-a-binary-tree-node-to-another/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 117. Populating Next Right Pointers in Each Node II</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 08:14:24 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[level order]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8933</guid>

					<description><![CDATA[Given a binary tree [crayon-69b249fab2995723023662/] Populate each next pointer to point to its next right node. If there is no next right node, the next&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given a binary tree</p>



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



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



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



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



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



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



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



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



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



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



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



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



<h2 class="wp-block-heading"><strong>Solution -2: Group nodes into levels</strong></h2>



<p>Use pre-order traversal to group nodes by levels.<br>Connects nodes in each level.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  Node* connect(Node* root) {
    vector&lt;vector&lt;Node*&gt;&gt; levels;
    dfs(root, 0, levels);
    for (auto&amp; nodes : levels)
      for(int i = 0; i &lt; nodes.size() - 1; ++i)
        nodes[i]-&gt;next = nodes[i+1]; 
    return root;
  }
private:
  void dfs(Node *root, int d, vector&lt;vector&lt;Node*&gt;&gt;&amp; levels) {
    if (!root) return;
    if (levels.size() &lt; d+1) levels.push_back({});
    levels[d].push_back(root);
    dfs(root-&gt;left, d + 1, levels);
    dfs(root-&gt;right, d + 1, levels);
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution -1: BFS level order traversal</strong></h2>



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



<p></p>



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

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



<h2 class="wp-block-heading"><strong>Solution 1: BFS w/o extra space</strong></h2>



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



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  Node* connect(Node* root) {
    Node* p = root;        
    while (p) {
      Node dummy;
      Node* c = &amp;dummy;
      while (p) {
        if (p-&gt;left)
          c-&gt;next = p-&gt;left, c = c-&gt;next;
        if (p-&gt;right)
          c-&gt;next = p-&gt;right, c = c-&gt;next;
        p = p-&gt;next;
      }
      p = dummy.next;
    }
    return root;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 173. Binary Search Tree Iterator</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-173-binary-search-tree-iterator/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-173-binary-search-tree-iterator/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 05:18:12 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[in order]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8908</guid>

					<description><![CDATA[Implement the&#160;BSTIterator&#160;class that represents an iterator over the&#160;in-order traversal&#160;of a binary search tree (BST): BSTIterator(TreeNode root)&#160;Initializes an object of the&#160;BSTIterator&#160;class. The&#160;root&#160;of the BST is given&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Implement the&nbsp;<code>BSTIterator</code>&nbsp;class that represents an iterator over the&nbsp;<strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank" rel="noreferrer noopener">in-order traversal</a></strong>&nbsp;of a binary search tree (BST):</p>



<ul class="wp-block-list"><li><code>BSTIterator(TreeNode root)</code>&nbsp;Initializes an object of the&nbsp;<code>BSTIterator</code>&nbsp;class. The&nbsp;<code>root</code>&nbsp;of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li><li><code>boolean hasNext()</code>&nbsp;Returns&nbsp;<code>true</code>&nbsp;if there exists a number in the traversal to the right of the pointer, otherwise returns&nbsp;<code>false</code>.</li><li><code>int next()</code>&nbsp;Moves the pointer to the right, then returns the number at the pointer.</li></ul>



<p>Notice that by initializing the pointer to a non-existent smallest number, the first call to&nbsp;<code>next()</code>&nbsp;will return the smallest element in the BST.</p>



<p>You may assume that&nbsp;<code>next()</code>&nbsp;calls will always be valid. That is, there will be at least a next number in the in-order traversal when&nbsp;<code>next()</code>&nbsp;is called.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
<strong>Output</strong>
</pre>


<p>[null, 3, 7, true, 9, true, 15, true, 20, false]</p>



<p><strong>Explanation</strong> BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False</p>



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



<ul class="wp-block-list"><li>The number of nodes in the tree is in the range&nbsp;<code>[1, 10<sup>5</sup>]</code>.</li><li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li><li>At most&nbsp;<code>10<sup>5</sup></code>&nbsp;calls will be made to&nbsp;<code>hasNext</code>, and&nbsp;<code>next</code>.</li></ul>



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



<ul class="wp-block-list"><li>Could you implement&nbsp;<code>next()</code>&nbsp;and&nbsp;<code>hasNext()</code>&nbsp;to run in average&nbsp;<code>O(1)</code>&nbsp;time and use&nbsp;<code>O(h)</code>&nbsp;memory, where&nbsp;<code>h</code>&nbsp;is the height of the tree?</li></ul>



<h2 class="wp-block-heading"><strong>Solution: In-order traversal using a stack</strong></h2>



<p>Use a stack to simulate in-order traversal.</p>



<p>Each next, we walk to the left most (smallest) node and push all the nodes along the path to the stack.</p>



<p>Then pop the top one t as return val, our next node to explore is the right child of t.</p>



<p>Time complexity: amortized O(1) for next() call.<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
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class BSTIterator {
public:
  BSTIterator(TreeNode* root) : root_(root) {}

  int next() {
    while (root_) {
      s_.push(root_);
      root_ = root_-&gt;left;
    }
    TreeNode* t = s_.top(); s_.pop();
    root_ = t-&gt;right;
    return t-&gt;val;
  }

  bool hasNext() {
    return (root_ || !s_.empty());
  }
private:
  TreeNode* root_;
  stack&lt;TreeNode*&gt; s_;
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj-&gt;next();
 * bool param_2 = obj-&gt;hasNext();
 */</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-173-binary-search-tree-iterator/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 199. Binary Tree Right Side View</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-199-binary-tree-right-side-view/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-199-binary-tree-right-side-view/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 03:43:18 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[level]]></category>
		<category><![CDATA[pre-order]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8894</guid>

					<description><![CDATA[Given the&#160;root&#160;of a binary tree, imagine yourself standing on the&#160;right side&#160;of it, return&#160;the values of the nodes you can see ordered from top to bottom.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the&nbsp;<code>root</code>&nbsp;of a binary tree, imagine yourself standing on the&nbsp;<strong>right side</strong>&nbsp;of it, return&nbsp;<em>the values of the nodes you can see ordered from top to bottom</em>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/02/14/tree.jpg" alt=""/></figure>



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



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



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



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



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



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



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



<h2 class="wp-block-heading"><strong>Solution: Pre-order traversal</strong></h2>



<p>By using pre-order traversal, the right most node will be the last one to visit in each level.</p>



<p>Time complexity: O(n)<br>Space complexity: O(|height|)</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;int&gt; rightSideView(TreeNode* root) {
    vector&lt;int&gt; ans;
    function&lt;void(TreeNode*, int)&gt; dfs = [&amp;](TreeNode* root, int d) {
      if (!root) return;
      if (ans.size() &lt; d + 1) ans.push_back(0);
      ans[d] = root-&gt;val;
      dfs(root-&gt;left, d + 1);
      dfs(root-&gt;right, d + 1);
    };
    dfs(root, 0);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-199-binary-tree-right-side-view/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 114. Flatten Binary Tree to Linked List</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-114-flatten-binary-tree-to-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-114-flatten-binary-tree-to-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 04:23:33 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8828</guid>

					<description><![CDATA[Given the&#160;root&#160;of a binary tree, flatten the tree into a &#8220;linked list&#8221;: The &#8220;linked list&#8221; should use the same&#160;TreeNode&#160;class where the&#160;right&#160;child pointer points to the&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the&nbsp;<code>root</code>&nbsp;of a binary tree, flatten the tree into a &#8220;linked list&#8221;:</p>



<ul class="wp-block-list"><li>The &#8220;linked list&#8221; should use the same&nbsp;<code>TreeNode</code>&nbsp;class where the&nbsp;<code>right</code>&nbsp;child pointer points to the next node in the list and the&nbsp;<code>left</code>&nbsp;child pointer is always&nbsp;<code>null</code>.</li><li>The &#8220;linked list&#8221; should be in the same order as a&nbsp;<a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank" rel="noreferrer noopener"><strong>pre-order</strong><strong>&nbsp;traversal</strong></a>&nbsp;of the binary tree.</li></ul>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg" alt=""/></figure>



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



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



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



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



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



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



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



<p><strong>Follow up:</strong>&nbsp;Can you flatten the tree in-place (with&nbsp;<code>O(1)</code>&nbsp;extra space)?</p>



<h2 class="wp-block-heading"><strong>Solution 1: Recursion</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag"># Author: Huahua
class Solution:
  def flatten(self, root: Optional[TreeNode]) -&amp;gt; None:
    &quot;&quot;&quot;
    Do not return anything, modify root in-place instead.
    &quot;&quot;&quot;
    def solve(root: Optional[TreeNode]):
      if not root: return None, None
      if not root.left and not root.right: return root, root
      l_head = l_tail = r_head = r_tail = None
      if root.left:
        l_head, l_tail = solve(root.left)
      if root.right:
        r_head, r_tail = solve(root.right)
      root.left = None
      root.right = l_head or r_head
      if l_tail:
        l_tail.right = r_head
      return root, r_tail or l_tail
    return solve(root)[0]</pre>
</div></div>



<p><strong>Solution 2: Unfolding</strong></p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag"># Author: Huahua
class Solution:
  def flatten(self, root: Optional[TreeNode]) -&gt; None:
    while root:
      if root.left:
        prev = root.left
        while prev.right: prev = prev.right
        prev.right = root.right
        root.right = root.left
        root.left = None
      root = root.right</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-114-flatten-binary-tree-to-linked-list/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[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;]]></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 decoding="async" 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 class="wp-block-list"><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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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 2003. Smallest Missing Genetic Value in Each Subtree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Nov 2021 07:38:06 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8743</guid>

					<description><![CDATA[There is a&#160;family tree&#160;rooted at&#160;0&#160;consisting of&#160;n&#160;nodes numbered&#160;0&#160;to&#160;n - 1. You are given a&#160;0-indexed&#160;integer array&#160;parents, where&#160;parents[i]&#160;is the parent for node&#160;i. Since node&#160;0&#160;is the&#160;root,&#160;parents[0] == -1. There&#8230;]]></description>
										<content:encoded><![CDATA[
<p>There is a&nbsp;<strong>family tree</strong>&nbsp;rooted at&nbsp;<code>0</code>&nbsp;consisting of&nbsp;<code>n</code>&nbsp;nodes numbered&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>. You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>parents</code>, where&nbsp;<code>parents[i]</code>&nbsp;is the parent for node&nbsp;<code>i</code>. Since node&nbsp;<code>0</code>&nbsp;is the&nbsp;<strong>root</strong>,&nbsp;<code>parents[0] == -1</code>.</p>



<p>There are&nbsp;<code>10<sup>5</sup></code>&nbsp;genetic values, each represented by an integer in the&nbsp;<strong>inclusive</strong>&nbsp;range&nbsp;<code>[1, 10<sup>5</sup>]</code>. You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>, where&nbsp;<code>nums[i]</code>&nbsp;is a&nbsp;<strong>distinct&nbsp;</strong>genetic value for node&nbsp;<code>i</code>.</p>



<p>Return&nbsp;<em>an array&nbsp;</em><code>ans</code><em>&nbsp;of length&nbsp;</em><code>n</code><em>&nbsp;where&nbsp;</em><code>ans[i]</code><em>&nbsp;is</em>&nbsp;<em>the&nbsp;<strong>smallest</strong>&nbsp;genetic value that is&nbsp;<strong>missing</strong>&nbsp;from the subtree rooted at node</em>&nbsp;<code>i</code>.</p>



<p>The&nbsp;<strong>subtree</strong>&nbsp;rooted at a node&nbsp;<code>x</code>&nbsp;contains node&nbsp;<code>x</code>&nbsp;and all of its&nbsp;<strong>descendant</strong>&nbsp;nodes.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/08/23/case-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> parents = [-1,0,0,2], nums = [1,2,3,4]
<strong>Output:</strong> [5,1,1,1]
<strong>Explanation:</strong> The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.
- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.
- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.
- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/08/23/case-2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]
<strong>Output:</strong> [7,1,1,4,2,1]
<strong>Explanation:</strong> The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.
- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.
- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.
- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.
- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.
- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]
<strong>Output:</strong> [1,1,1,1,1,1,1]
<strong>Explanation:</strong> The value 1 is missing from all the subtrees.
</pre>



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



<ul class="wp-block-list"><li><code>n == parents.length == nums.length</code></li><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= parents[i] &lt;= n - 1</code>&nbsp;for&nbsp;<code>i != 0</code></li><li><code>parents[0] == -1</code></li><li><code>parents</code>&nbsp;represents a valid tree.</li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li><li>Each&nbsp;<code>nums[i]</code>&nbsp;is distinct.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: DFS on a single path</strong></h2>



<p>One ancestors of node with value of 1 will have missing values greater than 1. We do a dfs on the path that from node with value 1 to the root.</p>



<p>Time complexity: O(n + max(nums))<br>Space complexity: O(n + max(nums)) </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;int&gt; smallestMissingValueSubtree(vector&lt;int&gt;&amp; parents, vector&lt;int&gt;&amp; nums) {
    const int n = parents.size();
    vector&lt;int&gt; ans(n, 1);
    vector&lt;int&gt; seen(100002);
    vector&lt;vector&lt;int&gt;&gt; g(n);
    for (int i = 1; i &lt; n; ++i)
      g[parents[i]].push_back(i);
    function&lt;void(int)&gt; dfs = [&amp;](int u) {
      if (seen[nums[u]]++) return;
      for (int v : g[u]) dfs(v);
    };
    int u = find(begin(nums), end(nums), 1) - begin(nums);
    for (int l = 1; u &lt; n &amp;&amp; u != -1; u = parents[u]) {
      dfs(u);
      while (seen[l]) ++l;
      ans[u] = l;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
