<?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 Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/tree/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/category/tree/</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.0.9</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>Tree Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/category/tree/</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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/">花花酱 LeetCode 3319. K-th Largest Perfect Subtree Size in Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>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 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 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 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><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><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/">花花酱 LeetCode 3319. K-th Largest Perfect Subtree Size in Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/">花花酱 LeetCode 2583. Kth Largest Sum in a Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>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 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 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><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><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/">花花酱 LeetCode 2583. Kth Largest Sum in a Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2416. Sum of Prefix Scores of Strings</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2416-sum-of-prefix-scores-of-strings/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2416-sum-of-prefix-scores-of-strings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 18 Sep 2022 19:44:55 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[prefix]]></category>
		<category><![CDATA[tire]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9832</guid>

					<description><![CDATA[<p>You are given an array&#160;words&#160;of size&#160;n&#160;consisting of&#160;non-empty&#160;strings. We define the&#160;score&#160;of a string&#160;word&#160;as the&#160;number&#160;of strings&#160;words[i]&#160;such that&#160;word&#160;is a&#160;prefix&#160;of&#160;words[i]. For example, if&#160;words = ["a", "ab", "abc", "cab"], then&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2416-sum-of-prefix-scores-of-strings/">花花酱 LeetCode 2416. Sum of Prefix Scores of Strings</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 2416. Sum of Prefix Scores of Strings - 刷题找工作 EP402" width="500" height="281" src="https://www.youtube.com/embed/OJ0PMH6M2MQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given an array&nbsp;<code>words</code>&nbsp;of size&nbsp;<code>n</code>&nbsp;consisting of&nbsp;<strong>non-empty</strong>&nbsp;strings.</p>



<p>We define the&nbsp;<strong>score</strong>&nbsp;of a string&nbsp;<code>word</code>&nbsp;as the&nbsp;<strong>number</strong>&nbsp;of strings&nbsp;<code>words[i]</code>&nbsp;such that&nbsp;<code>word</code>&nbsp;is a&nbsp;<strong>prefix</strong>&nbsp;of&nbsp;<code>words[i]</code>.</p>



<ul><li>For example, if&nbsp;<code>words = ["a", "ab", "abc", "cab"]</code>, then the score of&nbsp;<code>"ab"</code>&nbsp;is&nbsp;<code>2</code>, since&nbsp;<code>"ab"</code>&nbsp;is a prefix of both&nbsp;<code>"ab"</code>&nbsp;and&nbsp;<code>"abc"</code>.</li></ul>



<p>Return&nbsp;<em>an array&nbsp;</em><code>answer</code><em>&nbsp;of size&nbsp;</em><code>n</code><em>&nbsp;where&nbsp;</em><code>answer[i]</code><em>&nbsp;is the&nbsp;<strong>sum</strong>&nbsp;of scores of every&nbsp;<strong>non-empty</strong>&nbsp;prefix of&nbsp;</em><code>words[i]</code>.</p>



<p><strong>Note</strong>&nbsp;that a string is considered as a prefix of itself.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["abc","ab","bc","b"]
<strong>Output:</strong> [5,4,3,2]
<strong>Explanation:</strong> The answer for each string is the following:
- "abc" has 3 prefixes: "a", "ab", and "abc".
- There are 2 strings with the prefix "a", 2 strings with the prefix "ab", and 1 string with the prefix "abc".
The total is answer[0] = 2 + 2 + 1 = 5.
- "ab" has 2 prefixes: "a" and "ab".
- There are 2 strings with the prefix "a", and 2 strings with the prefix "ab".
The total is answer[1] = 2 + 2 = 4.
- "bc" has 2 prefixes: "b" and "bc".
- There are 2 strings with the prefix "b", and 1 string with the prefix "bc".
The total is answer[2] = 2 + 1 = 3.
- "b" has 1 prefix: "b".
- There are 2 strings with the prefix "b".
The total is answer[3] = 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["abcd"]
<strong>Output:</strong> [4]
<strong>Explanation:</strong>
"abcd" has 4 prefixes: "a", "ab", "abc", and "abcd".
Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4.
</pre>



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



<ul><li><code>1 &lt;= words.length &lt;= 1000</code></li><li><code>1 &lt;= words[i].length &lt;= 1000</code></li><li><code>words[i]</code>&nbsp;consists of lowercase English letters.</li></ul>



<h2><strong>Solution: Trie</strong></h2>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s1.png" alt="" class="wp-image-9836" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-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/09/lc-2416-ep402-s2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s2.png" alt="" class="wp-image-9837" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-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/09/lc-2416-ep402-s3.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s3.png" alt="" class="wp-image-9839" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2416-ep402-s3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Insert all the words into a tire whose node val is the number of substrings that have the current prefix.</p>



<p>During query time, sum up the values along the prefix path.</p>



<p>Time complexity: O(sum(len(word))<br>Space complexity: O(sum(len(word))</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
struct Trie {
  Trie* ch[26] = {};
  int cnt = 0;
  void insert(string_view s) {
    Trie* cur = this;
    for (char c : s) {
      if (!cur-&gt;ch[c - 'a']) 
        cur-&gt;ch[c - 'a'] = new Trie();
      cur = cur-&gt;ch[c - 'a'];
      ++cur-&gt;cnt;
    }
  }
  int query(string_view s) {
    Trie* cur = this;
    int ans = 0;
    for (char c : s) {
      cur = cur-&gt;ch[c - 'a'];
      ans += cur-&gt;cnt;
    }
    return ans;
  }
};
class Solution {
public:
  vector&lt;int&gt; sumPrefixScores(vector&lt;string&gt;&amp; words) {
    Trie* root = new Trie();
    for (const string&amp; w : words)
      root-&gt;insert(w);
    vector&lt;int&gt; ans;
    for (const string&amp; w : words)
      ans.push_back(root-&gt;query(w));
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2416-sum-of-prefix-scores-of-strings/">花花酱 LeetCode 2416. Sum of Prefix Scores of Strings</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-2416-sum-of-prefix-scores-of-strings/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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2265-count-nodes-equal-to-average-of-subtree/">花花酱 LeetCode 2265. Count Nodes Equal to Average of Subtree</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>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><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 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 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><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><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2265-count-nodes-equal-to-average-of-subtree/">花花酱 LeetCode 2265. Count Nodes Equal to Average of Subtree</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-2265-count-nodes-equal-to-average-of-subtree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2251. Number of Flowers in Full Bloom</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2251-number-of-flowers-in-full-bloom/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2251-number-of-flowers-in-full-bloom/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 28 Apr 2022 05:10:51 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[sweep line]]></category>
		<category><![CDATA[treemap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9692</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;2D integer array&#160;flowers, where&#160;flowers[i] = [starti, endi]&#160;means the&#160;ith&#160;flower will be in&#160;full bloom&#160;from&#160;starti&#160;to&#160;endi&#160;(inclusive). You are also given a&#160;0-indexed&#160;integer array&#160;persons&#160;of size&#160;n, where&#160;persons[i]&#160;is the time&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2251-number-of-flowers-in-full-bloom/">花花酱 LeetCode 2251. Number of Flowers in Full Bloom</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>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;2D integer array&nbsp;<code>flowers</code>, where&nbsp;<code>flowers[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>&nbsp;means the&nbsp;<code>i<sup>th</sup></code>&nbsp;flower will be in&nbsp;<strong>full bloom</strong>&nbsp;from&nbsp;<code>start<sub>i</sub></code>&nbsp;to&nbsp;<code>end<sub>i</sub></code>&nbsp;(<strong>inclusive</strong>). You are also given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>persons</code>&nbsp;of size&nbsp;<code>n</code>, where&nbsp;<code>persons[i]</code>&nbsp;is the time that the&nbsp;<code>i<sup>th</sup></code>&nbsp;person will arrive to see the flowers.</p>



<p>Return&nbsp;<em>an integer array&nbsp;</em><code>answer</code><em>&nbsp;of size&nbsp;</em><code>n</code><em>, where&nbsp;</em><code>answer[i]</code><em>&nbsp;is the&nbsp;<strong>number</strong>&nbsp;of flowers that are in full bloom when the&nbsp;</em><code>i<sup>th</sup></code><em>&nbsp;person arrives.</em></p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/03/02/ex1new.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]
<strong>Output:</strong> [1,2,2,2]
<strong>Explanation: </strong>The figure above shows the times when the flowers are in full bloom and when the people arrive.
For each person, we return the number of flowers in full bloom during their arrival.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/03/02/ex2new.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> flowers = [[1,10],[3,3]], persons = [3,3,2]
<strong>Output:</strong> [2,2,1]
<strong>Explanation:</strong> The figure above shows the times when the flowers are in full bloom and when the people arrive.
For each person, we return the number of flowers in full bloom during their arrival.
</pre>



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



<ul><li><code>1 &lt;= flowers.length &lt;= 5 * 10<sup>4</sup></code></li><li><code>flowers[i].length == 2</code></li><li><code>1 &lt;= start<sub>i</sub>&nbsp;&lt;= end<sub>i</sub>&nbsp;&lt;= 10<sup>9</sup></code></li><li><code>1 &lt;= persons.length &lt;= 5 * 10<sup>4</sup></code></li><li><code>1 &lt;= persons[i] &lt;= 10<sup>9</sup></code></li></ul>



<h2><strong>Solution: Prefix Sum + Binary Search</strong></h2>



<p>Use a treemap to store the counts (ordered by time t), when a flower begins to bloom at start, we increase m[start], when it dies at end, we decrease m[end+1]. prefix_sum[t] indicates the # of blooming flowers at time t.</p>



<p>For each people, use binary search to find the latest # of flowers before his arrival.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; fullBloomFlowers(vector&lt;vector&lt;int&gt;&gt;&amp; flowers, vector&lt;int&gt;&amp; persons) {
    map&lt;int, int&gt; m{{0, 0}};
    for (const auto&amp; f : flowers)
      ++m[f[0]], --m[f[1] + 1];    
    int sum = 0;
    for (auto&amp; [t, c] : m)
      c = sum += c;    
    vector&lt;int&gt; ans;    
    for (int t : persons)      
      ans.push_back(prev(m.upper_bound(t))-&gt;second);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2251-number-of-flowers-in-full-bloom/">花花酱 LeetCode 2251. Number of Flowers in Full Bloom</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-2251-number-of-flowers-in-full-bloom/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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2236-root-equals-sum-of-children/">花花酱 LeetCode 2236. Root Equals Sum of Children</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>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 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 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><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><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2236-root-equals-sum-of-children/">花花酱 LeetCode 2236. Root Equals Sum of Children</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-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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2196-create-binary-tree-from-descriptions/">花花酱 LeetCode 2196. Create Binary Tree From Descriptions</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>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><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 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 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><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><strong>Solution: Hashtable + Recursion</strong></h2>



<ol><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2196-create-binary-tree-from-descriptions/">花花酱 LeetCode 2196. Create Binary Tree From Descriptions</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-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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-222-count-complete-tree-nodes/">花花酱 LeetCode 222. Count Complete Tree Nodes</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 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" 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 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><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><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 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="(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 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="(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 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="(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 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="(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 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="(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 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="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image"><img/></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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-222-count-complete-tree-nodes/">花花酱 LeetCode 222. Count Complete Tree Nodes</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-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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2096-step-by-step-directions-from-a-binary-tree-node-to-another/">花花酱 LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another</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>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><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 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 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><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><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 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="(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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2096-step-by-step-directions-from-a-binary-tree-node-to-another/">花花酱 LeetCode 2096. Step-By-Step Directions From a Binary Tree Node to Another</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-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[<p>Given a binary tree [crayon-670ba1ef1c9fb593332055/] Populate each next pointer to point to its next right node. If there is no next right node, the next&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/">花花酱 LeetCode 117. Populating Next Right Pointers in Each Node II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a binary tree</p>



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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



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



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



<p></p>



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

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



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



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



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  Node* connect(Node* root) {
    Node* p = root;        
    while (p) {
      Node dummy;
      Node* c = &amp;dummy;
      while (p) {
        if (p-&gt;left)
          c-&gt;next = p-&gt;left, c = c-&gt;next;
        if (p-&gt;right)
          c-&gt;next = p-&gt;right, c = c-&gt;next;
        p = p-&gt;next;
      }
      p = dummy.next;
    }
    return root;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/">花花酱 LeetCode 117. Populating Next Right Pointers in Each Node II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-117-populating-next-right-pointers-in-each-node-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-173-binary-search-tree-iterator/">花花酱 LeetCode 173. Binary Search Tree Iterator</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>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><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 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><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><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><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-173-binary-search-tree-iterator/">花花酱 LeetCode 173. Binary Search Tree Iterator</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-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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-199-binary-tree-right-side-view/">花花酱 LeetCode 199. Binary Tree Right Side View</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>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 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><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><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-199-binary-tree-right-side-view/">花花酱 LeetCode 199. Binary Tree Right Side View</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-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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-114-flatten-binary-tree-to-linked-list/">花花酱 LeetCode 114. Flatten Binary Tree to Linked List</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>root</code>&nbsp;of a binary tree, flatten the tree into a &#8220;linked list&#8221;:</p>



<ul><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 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><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><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="crayon-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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-114-flatten-binary-tree-to-linked-list/">花花酱 LeetCode 114. Flatten Binary Tree to Linked List</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-114-flatten-binary-tree-to-linked-list/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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/">花花酱 LeetCode 2003. Smallest Missing Genetic Value in Each Subtree</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>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 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 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><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><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/">花花酱 LeetCode 2003. Smallest Missing Genetic Value in Each Subtree</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-2003-smallest-missing-genetic-value-in-each-subtree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2049. Count Nodes With the Highest Score</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2049-count-nodes-with-the-highest-score/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2049-count-nodes-with-the-highest-score/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 27 Oct 2021 03:13:10 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8646</guid>

					<description><![CDATA[<p>There is a&#160;binary&#160;tree rooted at&#160;0&#160;consisting of&#160;n&#160;nodes. The nodes are labeled from&#160;0&#160;to&#160;n - 1. You are given a&#160;0-indexed&#160;integer array&#160;parents&#160;representing the tree, where&#160;parents[i]&#160;is the parent of node&#160;i.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2049-count-nodes-with-the-highest-score/">花花酱 LeetCode 2049. Count Nodes With the Highest Score</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>There is a&nbsp;<strong>binary</strong>&nbsp;tree rooted at&nbsp;<code>0</code>&nbsp;consisting of&nbsp;<code>n</code>&nbsp;nodes. The nodes are labeled from&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>&nbsp;representing the tree, where&nbsp;<code>parents[i]</code>&nbsp;is the parent of node&nbsp;<code>i</code>. Since node&nbsp;<code>0</code>&nbsp;is the root,&nbsp;<code>parents[0] == -1</code>.</p>



<p>Each node has a&nbsp;<strong>score</strong>. To find the score of a node, consider if the node and the edges connected to it were&nbsp;<strong>removed</strong>. The tree would become one or more&nbsp;<strong>non-empty</strong>&nbsp;subtrees. The&nbsp;<strong>size</strong>&nbsp;of a subtree is the number of the nodes in it. The&nbsp;<strong>score</strong>&nbsp;of the node is the&nbsp;<strong>product of the sizes</strong>&nbsp;of all those subtrees.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>number</strong>&nbsp;of nodes that have the&nbsp;<strong>highest score</strong></em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/10/03/example-1.png" alt="example-1"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> parents = [-1,2,0,2,0]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
- The score of node 0 is: 3 * 1 = 3
- The score of node 1 is: 4 = 4
- The score of node 2 is: 1 * 1 * 2 = 2
- The score of node 3 is: 4 = 4
- The score of node 4 is: 4 = 4
The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/10/03/example-2.png" alt="example-2"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> parents = [-1,2,0]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
- The score of node 0 is: 2 = 2
- The score of node 1 is: 2 = 2
- The score of node 2 is: 1 * 1 = 1
The highest score is 2, and two nodes (node 0 and node 1) have the highest score.
</pre>



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



<ul><li><code>n == parents.length</code></li><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>parents[0] == -1</code></li><li><code>0 &lt;= parents[i] &lt;= n - 1</code>&nbsp;for&nbsp;<code>i != 0</code></li><li><code>parents</code>&nbsp;represents a valid binary tree.</li></ul>



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



<p>Write a function that returns the element of a subtree rooted at node.</p>



<p>We can compute the score based on:<br>1. size of the subtree(s)<br>2. # of children</p>



<p>Root is a special case whose score is max(c[0], 1) * max(c[1], 1).</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:
  int countHighestScoreNodes(vector&lt;int&gt;&amp; parents) {
    const int n = parents.size();
    long high = 0;
    int ans = 0;
    vector&lt;vector&lt;int&gt;&gt; tree(n);
    for (int i = 1; i &lt; n; ++i)
      tree[parents[i]].push_back(i);
    function&lt;int(int)&gt; dfs = [&amp;](int node) -&gt; int {      
      long c[2] = {0, 0};
      for (int i = 0; i &lt; tree[node].size(); ++i)
        c[i] = dfs(tree[node][i]);
      long score = 0;
      if (node == 0) // case #1: root
        score = max(c[0], 1l) * max(c[1], 1l);
      else if (tree[node].size() == 0) // case #2: leaf
        score = n - 1;
      else if (tree[node].size() == 1) // case #3: one child
        score = c[0] * (n - c[0] - 1);
      else // case #4: two children
        score = c[0] * c[1] * (n - c[0] - c[1] - 1);
      if (score &gt; high) {
        high = score;
        ans = 1;
      } else if (score == high) {
        ++ans;
      }
      return 1 + c[0] + c[1];
    };
    dfs(0);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2049-count-nodes-with-the-highest-score/">花花酱 LeetCode 2049. Count Nodes With the Highest Score</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-2049-count-nodes-with-the-highest-score/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
