<?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>recursion Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/recursion/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/recursion/</link>
	<description></description>
	<lastBuildDate>Tue, 10 May 2022 07:23:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>recursion Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/recursion/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 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 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>
		<item>
		<title>花花酱 LeetCode 1900. The Earliest and Latest Rounds Where Players Compete</title>
		<link>https://zxi.mytechroad.com/blog/recursion/leetcode-1900-the-earliest-and-latest-rounds-where-players-compete/</link>
					<comments>https://zxi.mytechroad.com/blog/recursion/leetcode-1900-the-earliest-and-latest-rounds-where-players-compete/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 12 Aug 2021 04:21:46 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[bitmask]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8574</guid>

					<description><![CDATA[<p>There is a tournament where&#160;n&#160;players are participating. The players are standing in a single row and are numbered from&#160;1&#160;to&#160;n&#160;based on their&#160;initial&#160;standing position (player&#160;1&#160;is the first&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1900-the-earliest-and-latest-rounds-where-players-compete/">花花酱 LeetCode 1900. The Earliest and Latest Rounds Where Players Compete</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 tournament where&nbsp;<code>n</code>&nbsp;players are participating. The players are standing in a single row and are numbered from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>&nbsp;based on their&nbsp;<strong>initial</strong>&nbsp;standing position (player&nbsp;<code>1</code>&nbsp;is the first player in the row, player&nbsp;<code>2</code>&nbsp;is the second player in the row, etc.).</p>



<p>The tournament consists of multiple rounds (starting from round number&nbsp;<code>1</code>). In each round, the&nbsp;<code>i<sup>th</sup></code>&nbsp;player from the front of the row competes against the&nbsp;<code>i<sup>th</sup></code>&nbsp;player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round.</p>



<ul><li>For example, if the row consists of players&nbsp;<code>1, 2, 4, 6, 7</code><ul><li>Player&nbsp;<code>1</code>&nbsp;competes against player&nbsp;<code>7</code>.</li><li>Player&nbsp;<code>2</code>&nbsp;competes against player&nbsp;<code>6</code>.</li><li>Player&nbsp;<code>4</code>&nbsp;automatically advances to the next round.</li></ul></li></ul>



<p>After each round is over, the winners are lined back up in the row based on the&nbsp;<strong>original ordering</strong>&nbsp;assigned to them initially (ascending order).</p>



<p>The players numbered&nbsp;<code>firstPlayer</code>&nbsp;and&nbsp;<code>secondPlayer</code>&nbsp;are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may&nbsp;<strong>choose</strong>&nbsp;the outcome of this round.</p>



<p>Given the integers&nbsp;<code>n</code>,&nbsp;<code>firstPlayer</code>, and&nbsp;<code>secondPlayer</code>, return&nbsp;<em>an integer array containing two values, the&nbsp;<strong>earliest</strong>&nbsp;possible round number and the&nbsp;<strong>latest</strong>&nbsp;possible round number in which these two players will compete against each other, respectively</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 11, firstPlayer = 2, secondPlayer = 4
<strong>Output:</strong> [3,4]
<strong>Explanation:</strong>
One possible scenario which leads to the earliest round number:
First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Second round: 2, 3, 4, 5, 6, 11
Third round: 2, 3, 4
One possible scenario which leads to the latest round number:
First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Second round: 1, 2, 3, 4, 5, 6
Third round: 1, 2, 4
Fourth round: 2, 4
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, firstPlayer = 1, secondPlayer = 5
<strong>Output:</strong> [1,1]
<strong>Explanation:</strong> The players numbered 1 and 5 compete in the first round.
There is no way to make them compete in any other round.
</pre>



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



<ul><li><code>2 &lt;= n &lt;= 28</code></li><li><code>1 &lt;= firstPlayer &lt; secondPlayer &lt;= n</code></li></ul>



<h2><strong>Solution 1: Simulation using recursion</strong></h2>



<p>All possible paths, <br>Time complexity: O(n<sup>2</sup>*2<sup>n</sup>)<br>Space complexity: O(logn)</p>



<p>dfs(s, i, j, d) := let i battle with j at round d, given s (binary mask of dead players).</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; earliestAndLatest(int n, int a, int b) {
    vector&lt;int&gt; ans{INT_MAX, INT_MIN};    
    function&lt;void(int, int, int, int)&gt; dfs = [&amp;](int s, int i, int j, int d) {
      while (i &lt; j &amp;&amp; s &gt;&gt; i &amp; 1) ++i;
      while (i &lt; j &amp;&amp; s &gt;&gt; j &amp; 1) --j;
      if (i &gt;= j) {
        return dfs(s, 1, n, d + 1);
      } else if (i == a &amp;&amp; j == b) {
        ans[0] = min(ans[0], d);
        ans[1] = max(ans[1], d);
      } else {
        if (i != a &amp;&amp; i != b)
          dfs(s | (1 &lt;&lt; i), i + 1, j - 1, d);
        if (j != a &amp;&amp; j != b)
          dfs(s | (1 &lt;&lt; j), i + 1, j - 1, d);
      }
    };
    dfs(0, 1, n, 1);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1900-the-earliest-and-latest-rounds-where-players-compete/">花花酱 LeetCode 1900. The Earliest and Latest Rounds Where Players Compete</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/recursion/leetcode-1900-the-earliest-and-latest-rounds-where-players-compete/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1896. Minimum Cost to Change the Final Value of Expression</title>
		<link>https://zxi.mytechroad.com/blog/recursion/leetcode-1896-minimum-cost-to-change-the-final-value-of-expression/</link>
					<comments>https://zxi.mytechroad.com/blog/recursion/leetcode-1896-minimum-cost-to-change-the-final-value-of-expression/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 10 Aug 2021 06:27:59 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[expression]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8558</guid>

					<description><![CDATA[<p>You are given a&#160;valid&#160;boolean expression as a string&#160;expression&#160;consisting of the characters&#160;'1','0','&#38;'&#160;(bitwise&#160;AND&#160;operator),'&#124;'&#160;(bitwise&#160;OR&#160;operator),'(', and&#160;')'. For example,&#160;"()1&#124;1"&#160;and&#160;"(1)&#38;()"&#160;are&#160;not valid&#160;while&#160;"1",&#160;"(((1))&#124;(0))", and&#160;"1&#124;(0&#38;(1))"&#160;are&#160;valid&#160;expressions. Return&#160;the&#160;minimum cost&#160;to change the final value of the expression.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1896-minimum-cost-to-change-the-final-value-of-expression/">花花酱 LeetCode 1896. Minimum Cost to Change the Final Value of Expression</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>valid</strong>&nbsp;boolean expression as a string&nbsp;<code>expression</code>&nbsp;consisting of the characters&nbsp;<code>'1'</code>,<code>'0'</code>,<code>'&amp;'</code>&nbsp;(bitwise&nbsp;<strong>AND</strong>&nbsp;operator),<code>'|'</code>&nbsp;(bitwise&nbsp;<strong>OR</strong>&nbsp;operator),<code>'('</code>, and&nbsp;<code>')'</code>.</p>



<ul><li>For example,&nbsp;<code>"()1|1"</code>&nbsp;and&nbsp;<code>"(1)&amp;()"</code>&nbsp;are&nbsp;<strong>not valid</strong>&nbsp;while&nbsp;<code>"1"</code>,&nbsp;<code>"(((1))|(0))"</code>, and&nbsp;<code>"1|(0&amp;(1))"</code>&nbsp;are&nbsp;<strong>valid</strong>&nbsp;expressions.</li></ul>



<p>Return<em>&nbsp;the&nbsp;<strong>minimum cost</strong>&nbsp;to change the final value of the expression</em>.</p>



<ul><li>For example, if&nbsp;<code>expression = "1|1|(0&amp;0)&amp;1"</code>, its&nbsp;<strong>value</strong>&nbsp;is&nbsp;<code>1|1|(0&amp;0)&amp;1 = 1|1|0&amp;1 = 1|0&amp;1 = 1&amp;1 = 1</code>. We want to apply operations so that the<strong>&nbsp;new</strong>&nbsp;expression evaluates to&nbsp;<code>0</code>.</li></ul>



<p>The&nbsp;<strong>cost</strong>&nbsp;of changing the final value of an expression is the&nbsp;<strong>number of operations</strong>&nbsp;performed on the expression. The types of&nbsp;<strong>operations</strong>&nbsp;are described as follows:</p>



<ul><li>Turn a&nbsp;<code>'1'</code>&nbsp;into a&nbsp;<code>'0'</code>.</li><li>Turn a&nbsp;<code>'0'</code>&nbsp;into a&nbsp;<code>'1'</code>.</li><li>Turn a&nbsp;<code>'&amp;'</code>&nbsp;into a&nbsp;<code>'|'</code>.</li><li>Turn a&nbsp;<code>'|'</code>&nbsp;into a&nbsp;<code>'&amp;'</code>.</li></ul>



<p><strong>Note:</strong>&nbsp;<code>'&amp;'</code>&nbsp;does&nbsp;<strong>not</strong>&nbsp;take precedence over&nbsp;<code>'|'</code>&nbsp;in the&nbsp;<strong>order of calculation</strong>. Evaluate parentheses&nbsp;<strong>first</strong>, then in&nbsp;<strong>left-to-right</strong>&nbsp;order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "1&amp;(0|1)"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can turn "1&amp;(0<strong>|</strong>1)" into "1&amp;(0<strong>&amp;</strong>1)" by changing the '|' to a '&amp;' using 1 operation.
The new expression evaluates to 0. 
</pre>



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



<pre class="crayon-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; expression = &quot;(0&amp;amp;0)&amp;amp;(0&amp;amp;0&amp;amp;0)&quot;
&lt;strong&gt;Output:&lt;/strong&gt; 3
&lt;strong&gt;Explanation:&lt;/strong&gt; We can turn &quot;(0&lt;strong&gt;&amp;amp;0&lt;/strong&gt;)&lt;strong&gt;&lt;u&gt;&amp;amp;&lt;/u&gt;&lt;/strong&gt;(0&amp;amp;0&amp;amp;0)&quot; into &quot;(0&lt;strong&gt;|1&lt;/strong&gt;)&lt;strong&gt;|&lt;/strong&gt;(0&amp;amp;0&amp;amp;0)&quot; using 3 operations.
The new expression evaluates to 1.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> expression = "(0|(1|0&amp;1))"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We can turn "(0|(<strong>1</strong>|0&amp;1))" into "(0|(<strong>0</strong>|0&amp;1))" using 1 operation.
The new expression evaluates to 0.</pre>



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



<ul><li><code>1 &lt;= expression.length &lt;= 10<sup>5</sup></code></li><li><code>expression</code>&nbsp;only contains&nbsp;<code>'1'</code>,<code>'0'</code>,<code>'&amp;'</code>,<code>'|'</code>,<code>'('</code>, and&nbsp;<code>')'</code></li><li>All parentheses&nbsp;are properly matched.</li><li>There will be no empty parentheses (i.e:&nbsp;<code>"()"</code>&nbsp;is not a substring of&nbsp;<code>expression</code>).</li></ul>



<h2><strong>Solution: DP, Recursion / Simulation w/ Stack</strong></h2>



<p>For each expression, stores the min cost to change value to 0 and 1.</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">class Solution {
public:
  int minOperationsToFlip(string expression) {
    stack&lt;array&lt;int, 3&gt;&gt; s;
    s.push({0, 0, 0});
    for (char e : expression) {
      if (e == '(')
        s.push({0, 0, 0});
      else if (e == '&amp;' || e == '|')
        s.top()[2] = e;
      else {        
        if (isdigit(e)) s.push({e != '0', e != '1', 0});
        auto [r0, r1, _] = s.top(); s.pop();
        auto [l0, l1, op] = s.top(); s.pop();
        if (op == '&amp;') {
          s.push({min(l0, r0),
                  min(l1 + r1, min(l1, r1) + 1),
                  0});
        } else if (op == '|') {
          s.push({min(l0 + r0, min(l0, r0) + 1),
                  min(l1, r1),
                  0});
        } else {
          s.push({r0, r1, 0});
        }
      }
    }
    return max(s.top()[0], s.top()[1]);
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1896-minimum-cost-to-change-the-final-value-of-expression/">花花酱 LeetCode 1896. Minimum Cost to Change the Final Value of Expression</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/recursion/leetcode-1896-minimum-cost-to-change-the-final-value-of-expression/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1688. Count of Matches in Tournament</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1688-count-of-matches-in-tournament/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1688-count-of-matches-in-tournament/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Dec 2020 20:15:36 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[O(logn)]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7799</guid>

					<description><![CDATA[<p>You are given an integer&#160;n, the number of teams in a tournament that has strange rules: If the current number of teams is&#160;even, each team&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1688-count-of-matches-in-tournament/">花花酱 LeetCode 1688. Count of Matches in Tournament</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 an integer&nbsp;<code>n</code>, the number of teams in a tournament that has strange rules:</p>



<ul><li>If the current number of teams is&nbsp;<strong>even</strong>, each team gets paired with another team. A total of&nbsp;<code>n / 2</code>&nbsp;matches are played, and&nbsp;<code>n / 2</code>&nbsp;teams advance to the next round.</li><li>If the current number of teams is&nbsp;<strong>odd</strong>, one team randomly advances in the tournament, and the rest gets paired. A total of&nbsp;<code>(n - 1) / 2</code>&nbsp;matches are played, and&nbsp;<code>(n - 1) / 2 + 1</code>&nbsp;teams advance to the next round.</li></ul>



<p>Return&nbsp;<em>the number of matches played in the tournament until a winner is decided.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7
<strong>Output:</strong> 6
<strong>Explanation:</strong> Details of the tournament: 
- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.
- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 3 + 2 + 1 = 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 14
<strong>Output:</strong> 13
<strong>Explanation:</strong> Details of the tournament:
- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.
- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.
- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.
- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.
Total number of matches = 7 + 3 + 2 + 1 = 13.
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 200</code></li></ul>



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



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



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

<pre class="crayon-plain-tag">// Ver 1
class Solution {
public:
  int numberOfMatches(int n) {
    int ans = 0;
    while (n &amp;gt; 1) {
      ans += n / 2 + (n &amp; 1);
      n /= 2;
    }
    return ans;
  }
};
// Ver 2
class Solution {
public:
  int numberOfMatches(int n) {
    return n &amp;gt; 1 ? n / 2 + (n &amp; 1) + numberOfMatches(n / 2) : 0;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1688-count-of-matches-in-tournament/">花花酱 LeetCode 1688. Count of Matches in Tournament</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-1688-count-of-matches-in-tournament/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1600. Throne Inheritance</title>
		<link>https://zxi.mytechroad.com/blog/recursion/leetcode-1600-throne-inheritance/</link>
					<comments>https://zxi.mytechroad.com/blog/recursion/leetcode-1600-throne-inheritance/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Sep 2020 08:11:05 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7425</guid>

					<description><![CDATA[<p>A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1600-throne-inheritance/">花花酱 LeetCode 1600. Throne Inheritance</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>A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.</p>



<p>The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let&#8217;s define the recursive function&nbsp;<code>Successor(x, curOrder)</code>, which given a person&nbsp;<code>x</code>&nbsp;and the inheritance order so far, returns who should be the next person after&nbsp;<code>x</code>&nbsp;in the order of inheritance.</p>



<pre class="crayon-plain-tag">Successor(x, curOrder):
    if x has no children or all of x's children are in curOrder:
        if x is the king return null
        else return Successor(x's parent, curOrder)
    else return x's oldest child who's not in curOrder</pre>



<p>For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice&#8217;s son Jack.</p>



<ol><li>In the beginning,&nbsp;<code>curOrder</code>&nbsp;will be&nbsp;<code>["king"]</code>.</li><li>Calling&nbsp;<code>Successor(king, curOrder)</code>&nbsp;will return Alice, so we append to&nbsp;<code>curOrder</code>&nbsp;to get&nbsp;<code>["king", "Alice"]</code>.</li><li>Calling&nbsp;<code>Successor(Alice, curOrder)</code>&nbsp;will return Jack, so we append to&nbsp;<code>curOrder</code>&nbsp;to get&nbsp;<code>["king", "Alice", "Jack"]</code>.</li><li>Calling&nbsp;<code>Successor(Jack, curOrder)</code>&nbsp;will return Bob, so we append to&nbsp;<code>curOrder</code>&nbsp;to get&nbsp;<code>["king", "Alice", "Jack", "Bob"]</code>.</li><li>Calling&nbsp;<code>Successor(Bob, curOrder)</code>&nbsp;will return&nbsp;<code>null</code>. Thus the order of inheritance will be&nbsp;<code>["king", "Alice", "Jack", "Bob"]</code>.</li></ol>



<p>Using the above function, we can always obtain a unique order of inheritance.</p>



<p>Implement the&nbsp;<code>ThroneInheritance</code>&nbsp;class:</p>



<ul><li><code>ThroneInheritance(string kingName)</code>&nbsp;Initializes an object of the&nbsp;<code>ThroneInheritance</code>&nbsp;class. The name of the king is given as part of the constructor.</li><li><code>void birth(string parentName, string childName)</code>&nbsp;Indicates that&nbsp;<code>parentName</code>&nbsp;gave birth to&nbsp;<code>childName</code>.</li><li><code>void death(string name)</code>&nbsp;Indicates the death of&nbsp;<code>name</code>. The death of the person doesn&#8217;t affect the&nbsp;<code>Successor</code>&nbsp;function nor the current inheritance order. You can treat it as just marking the person as dead.</li><li><code>string[] getInheritanceOrder()</code>&nbsp;Returns a list representing the current order of inheritance&nbsp;<strong>excluding</strong>&nbsp;dead people.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"]
[["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]]
<strong>Output</strong>
[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]
<strong>Explanation</strong>
ThroneInheritance t= new ThroneInheritance("king"); // order: <strong>king</strong>
t.birth("king", "andy"); // order: king &gt; <strong>andy</strong>
t.birth("king", "bob"); // order: king &gt; andy &gt; <strong>bob</strong>
t.birth("king", "catherine"); // order: king &gt; andy &gt; bob &gt; <strong>catherine</strong>
t.birth("andy", "matthew"); // order: king &gt; andy &gt; <strong>matthew</strong> &gt; bob &gt; catherine
t.birth("bob", "alex"); // order: king &gt; andy &gt; matthew &gt; bob &gt; <strong>alex</strong> &gt; catherine
t.birth("bob", "asha"); // order: king &gt; andy &gt; matthew &gt; bob &gt; alex &gt; <strong>asha</strong> &gt; catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
t.death("bob"); // order: king &gt; andy &gt; matthew &gt; <strong><s>bob</s></strong> &gt; alex &gt; asha &gt; catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"]
</p>
</pre>



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



<ul><li><code>1 &lt;= kingName.length, parentName.length, childName.length, name.length &lt;= 15</code></li><li><code>kingName</code>,&nbsp;<code>parentName</code>,&nbsp;<code>childName</code>, and&nbsp;<code>name</code>&nbsp;consist of lowercase English letters only.</li><li>All arguments&nbsp;<code>childName</code>&nbsp;and&nbsp;<code>kingName</code>&nbsp;are&nbsp;<strong>distinct</strong>.</li><li>All&nbsp;<code>name</code>&nbsp;arguments of&nbsp;<code>death</code>&nbsp;will be passed to either the constructor or as&nbsp;<code>childName</code>&nbsp;to&nbsp;<code>birth</code>&nbsp;first.</li><li>For each call to&nbsp;<code>birth(parentName, childName)</code>, it is guaranteed that&nbsp;<code>parentName</code>&nbsp;is alive.</li><li>At most&nbsp;<code>10<sup>5</sup></code>&nbsp;calls will be made to&nbsp;<code>birth</code>&nbsp;and&nbsp;<code>death</code>.</li><li>At most&nbsp;<code>10</code>&nbsp;calls will be made to&nbsp;<code>getInheritanceOrder</code>.</li></ul>



<h2><strong>Solution: HashTable + DFS</strong></h2>



<p>Record :<br>1. mapping from parent to children (ordered)<br>2. who has dead</p>



<p>Time complexity: getInheritanceOrder O(n), other O(1)<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 ThroneInheritance {
public:
  ThroneInheritance(string kingName): king_(kingName) {
    m_[kingName] = {};
  }

  void birth(string parentName, string childName) {
    m_[parentName].push_back(childName);
  }

  void death(string name) {
    dead_.insert(name);
  }

  vector&lt;string&gt; getInheritanceOrder() {
    vector&lt;string&gt; ans;
    function&lt;void(const string&amp;)&gt; dfs = [&amp;](const string&amp; name) {
      if (!dead_.count(name)) ans.push_back(name);
      for (const string&amp; child: m_[name]) dfs(child);
    };
    dfs(king_);
    return ans;
  }
private:  
  string king_;  
  unordered_map&lt;string, vector&lt;string&gt;&gt; m_; // parent -&gt; list[children]
  unordered_set&lt;string&gt; dead_;
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class ThroneInheritance:
  def __init__(self, kingName: str):
    self.kingName = kingName
    self.family = defaultdict(list)    
    self.dead = set()

  def birth(self, parentName: str, childName: str) -&gt; None:
    self.family[parentName].append(childName)

  def death(self, name: str) -&gt; None:
    self.dead.add(name)

  def getInheritanceOrder(self) -&gt; List[str]:
    order = []
    def dfs(name: str):
      if name not in self.dead: order.append(name)
      for child in self.family[name]: dfs(child)
    dfs(self.kingName)
    return order</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1600-throne-inheritance/">花花酱 LeetCode 1600. Throne Inheritance</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/recursion/leetcode-1600-throne-inheritance/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1569. Number of Ways to Reorder Array to Get Same BST</title>
		<link>https://zxi.mytechroad.com/blog/recursion/leetcode-1569-number-of-ways-to-reorder-array-to-get-same-bst/</link>
					<comments>https://zxi.mytechroad.com/blog/recursion/leetcode-1569-number-of-ways-to-reorder-array-to-get-same-bst/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Aug 2020 08:48:13 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7320</guid>

					<description><![CDATA[<p>Given an array&#160;nums&#160;that represents a permutation of integers from&#160;1&#160;to&#160;n. We are going to construct a binary search tree (BST) by inserting the elements of&#160;nums&#160;in&#160;order into&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1569-number-of-ways-to-reorder-array-to-get-same-bst/">花花酱 LeetCode 1569. Number of Ways to Reorder Array to Get Same BST</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an array&nbsp;<code>nums</code>&nbsp;that represents a permutation of integers from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>. We are going to construct a binary search tree (BST) by inserting the elements of&nbsp;<code>nums</code>&nbsp;in&nbsp;order into an initially empty BST. Find the number of different ways to reorder&nbsp;<code>nums</code>&nbsp;so that the constructed BST is identical to that formed from the original array&nbsp;<code>nums</code>.</p>



<p>For example, given&nbsp;<code>nums = [2,1,3]</code>, we will have 2 as the root, 1 as a left child, and 3 as a right child. The array&nbsp;<code>[2,3,1]</code>&nbsp;also yields the same BST but&nbsp;<code>[3,2,1]</code>&nbsp;yields a different BST.</p>



<p>Return&nbsp;<em>the number of ways to reorder</em>&nbsp;<code>nums</code>&nbsp;<em>such that the BST formed is identical to the original BST formed from</em>&nbsp;<code>nums</code>.</p>



<p>Since the answer may be very large,&nbsp;<strong>return it modulo&nbsp;</strong><code>10^9 + 7</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/08/12/bb.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> 1
<strong>Explanation: </strong>We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/08/12/ex1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,4,5,1,2]
<strong>Output:</strong> 5
<strong>Explanation: </strong>The following 5 arrays will yield the same BST: 
[3,1,2,4,5]
[3,1,4,2,5]
[3,1,4,5,2]
[3,4,1,2,5]
[3,4,1,5,2]
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/08/12/ex4.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> 0
<strong>Explanation: </strong>There are no other orderings of nums that will yield the same BST.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/08/12/abc.png" alt=""/></figure>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [9,4,2,1,3,6,5,7,8,14,11,10,12,13,16,15,17,18]
<strong>Output:</strong> 216212978
<strong>Explanation: </strong>The number of ways to reorder nums to get the same BST is 3216212999. Taking this number modulo 10^9 + 7 gives 216212978.
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 1000</code></li><li><code>1 &lt;= nums[i] &lt;= nums.length</code></li><li>All integers in&nbsp;<code>nums</code>&nbsp;are&nbsp;<strong>distinct</strong>.</li></ul>



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



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



<p>For a given root (first element of the array), we can split the array into left children (nums[i] &lt; nums[0]) and right children (nums[i] &gt; nums[0]). Assuming there are l nodes for the left and r nodes for the right. We have C(l + r, l) different ways to insert l elements into a (l + r) sized array. Within node l / r nodes, we have ways(left) / ways(right) different ways to re-arrange those nodes. So the total # of ways is:<br>C(l + r, l) * ways(l) * ways(r)<br>Don&#8217;t forget to minus one for the final answer.</p>



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



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

<pre class="crayon-plain-tag">class Solution {
public:
  int numOfWays(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    const int kMod = 1e9 + 7;
    vector&lt;vector&lt;int&gt;&gt; cnk(n + 1, vector&lt;int&gt;(n + 1, 1));    
    for (int i = 1; i &lt;= n; ++i)      
      for (int j = 1; j &lt; i; ++j)
        cnk[i][j] = (cnk[i - 1][j] + cnk[i - 1][j - 1]) % kMod;    
    function&lt;int(vector&lt;int&gt;)&gt; trees = [&amp;](const vector&lt;int&gt;&amp; nums) {
      const int n = nums.size();
      if (n &lt;= 2) return 1;
      vector&lt;int&gt; left;
      vector&lt;int&gt; right;
      for (int i = 1; i &lt; nums.size(); ++i)
        if (nums[i] &lt; nums[0]) left.push_back(nums[i]);
        else right.push_back(nums[i]);
      long ans = cnk[n - 1][left.size()];
      ans = (ans * trees(left)) % kMod;      
      ans = (ans * trees(right)) % kMod;      
      return static_cast&lt;int&gt;(ans);
    };
    return trees(nums) - 1;
  } 
};</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def numOfWays(self, nums: List[int]) -&gt; int:
    def ways(nums):
      if len(nums) &lt;= 2: return 1
      l = [x for x in nums if x &lt; nums[0]]
      r = [x for x in nums if x &gt; nums[0]]
      return comb(len(l) + len(r), len(l)) * ways(l) * ways(r)
    return (ways(nums) - 1) % (10**9 + 7)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-1569-number-of-ways-to-reorder-array-to-get-same-bst/">花花酱 LeetCode 1569. Number of Ways to Reorder Array to Get Same BST</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/recursion/leetcode-1569-number-of-ways-to-reorder-array-to-get-same-bst/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 19 Jul 2020 05:14:52 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[postorder]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7119</guid>

					<description><![CDATA[<p>Given a tree (i.e. a connected, undirected graph that has no cycles) consisting of&#160;n&#160;nodes numbered from&#160;0&#160;to&#160;n - 1&#160;and exactly&#160;n - 1&#160;edges. The&#160;root&#160;of the tree is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/">花花酱 LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label</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 tree (i.e. a connected, undirected graph that has no cycles) consisting of&nbsp;<code>n</code>&nbsp;nodes numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;and exactly&nbsp;<code>n - 1</code>&nbsp;<code>edges</code>. The&nbsp;<strong>root</strong>&nbsp;of the tree is the node&nbsp;<code>0</code>, and each node of the tree has&nbsp;<strong>a label</strong>&nbsp;which is a lower-case character given in the string&nbsp;<code>labels</code>&nbsp;(i.e. The node with the number&nbsp;<code>i</code>&nbsp;has the label&nbsp;<code>labels[i]</code>).</p>



<p>The&nbsp;<code>edges</code>&nbsp;array is given on the form&nbsp;<code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>, which means there is an edge between nodes&nbsp;<code>a<sub>i</sub></code>&nbsp;and&nbsp;<code>b<sub>i</sub></code>&nbsp;in the tree.</p>



<p>Return&nbsp;<em>an array of size&nbsp;<code>n</code></em>&nbsp;where&nbsp;<code>ans[i]</code>&nbsp;is the number of nodes in the subtree of the&nbsp;<code>i<sup>th</sup></code>&nbsp;node which have the same label as node&nbsp;<code>i</code>.</p>



<p>A&nbsp;subtree&nbsp;of a tree&nbsp;<code>T</code>&nbsp;is the tree consisting of a node in&nbsp;<code>T</code>&nbsp;and all of its descendant&nbsp;nodes.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/07/01/q3e1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
<strong>Output:</strong> [2,1,1,1,1,1,1]
<strong>Explanation:</strong> Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/07/01/q3e2.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"
<strong>Output:</strong> [4,2,1,1]
<strong>Explanation:</strong> The sub-tree of node 2 contains only node 2, so the answer is 1.
The sub-tree of node 3 contains only node 3, so the answer is 1.
The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.
The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/07/01/q3e3.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"
<strong>Output:</strong> [3,2,1,1,1]
</pre>



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



<pre class="crayon-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; n = 6, edges = [[0,1],[0,2],[1,3],[3,4],[4,5]], labels = &quot;cbabaa&quot;
&lt;strong&gt;Output:&lt;/strong&gt; [1,2,1,1,2,1]</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, edges = [[0,1],[1,2],[2,3],[3,4],[4,5],[5,6]], labels = "aaabaaa"
<strong>Output:</strong> [6,5,4,1,3,2,1]
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 10^5</code></li><li><code>edges.length == n - 1</code></li><li><code>edges[i].length == 2</code></li><li><code>0 &lt;= a<sub>i</sub>,&nbsp;b<sub>i</sub>&nbsp;&lt; n</code></li><li><code>a<sub>i</sub>&nbsp;!=&nbsp;b<sub>i</sub></code></li><li><code>labels.length == n</code></li><li><code>labels</code>&nbsp;is consisting of only of lower-case English letters.</li></ul>



<h2><strong>Solution: Post order traversal + hashtable</strong></h2>



<p>For each label, record the count. When visiting a node, we first record the current count of its label as before, and traverse its children, when done, increment the current count, ans[i] = current &#8211;  before.</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:
  vector&lt;int&gt; countSubTrees(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges, 
                            string_view labels) {
    vector&lt;vector&lt;int&gt;&gt; g(n);    
    for (const auto&amp; e : edges) {
      g[e[0]].push_back(e[1]);
      g[e[1]].push_back(e[0]);
    }
    vector&lt;int&gt; seen(n);
    vector&lt;int&gt; count(26);
    vector&lt;int&gt; ans(n);
    function&lt;void(int)&gt; postOrder = [&amp;](int i) {
      if (seen[i]++) return;
      int before = count[labels[i] - 'a'];
      for (int j : g[i]) postOrder(j);        
      ans[i] = ++count[labels[i] - 'a'] - before;
    };
    postOrder(0);
    return ans;
  }
};</pre>

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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  private List&lt;List&lt;Integer&gt;&gt; g;
  private String labels;
  private int[] ans;
  private int[] seen;
  private int[] count;
  
  public int[] countSubTrees(int n, int[][] edges, String labels) {
    this.g = new ArrayList&lt;List&lt;Integer&gt;&gt;(n);
    this.labels = labels; 
    for (int i = 0; i &lt; n; ++i)
      this.g.add(new ArrayList&lt;Integer&gt;());
    for (int[] e : edges) {
      this.g.get(e[0]).add(e[1]);
      this.g.get(e[1]).add(e[0]);
    }
    this.ans = new int[n];
    this.seen = new int[n];
    this.count = new int[26];
    this.postOrder(0);
    return ans;
  }
  
  private void postOrder(int i) {
    if (this.seen[i]++ &gt; 0) return;
    int before = this.count[this.labels.charAt(i) - 'a'];
    for (int j : this.g.get(i)) this.postOrder(j);
    this.ans[i] = ++this.count[this.labels.charAt(i) - 'a'] - before;    
  }
}</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def countSubTrees(self, n: int, edges: List[List[int]], 
                    labels: str) -&gt; List[int]:
    g = [[] for _ in range(n)]
    for u, v in edges:
      g[u].append(v)
      g[v].append(u)
    seen = [False] * n
    count = [0] * 26
    ans = [0] * n
    def postOrder(i):
      if seen[i]: return
      seen[i] = True
      before = count[ord(labels[i]) - ord('a')]
      for j in g[i]: postOrder(j)
      count[ord(labels[i]) - ord('a')] += 1
      ans[i] = count[ord(labels[i]) - ord('a')] - before
    postOrder(0)
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/">花花酱 LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label</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-1519-number-of-nodes-in-the-sub-tree-with-the-same-label/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1448. Count Good Nodes in Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1448-count-good-nodes-in-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1448-count-good-nodes-in-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 18 May 2020 02:12:45 +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=6785</guid>

					<description><![CDATA[<p>Given a binary tree&#160;root, a node&#160;X&#160;in the tree is named&#160;good&#160;if in the path from root to&#160;X&#160;there are no nodes with a value&#160;greater than&#160;X. Return the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1448-count-good-nodes-in-binary-tree/">花花酱 LeetCode 1448. Count Good Nodes 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>Given a binary tree&nbsp;<code>root</code>, a node&nbsp;<em>X</em>&nbsp;in the tree is named&nbsp;<strong>good</strong>&nbsp;if in the path from root to&nbsp;<em>X</em>&nbsp;there are no nodes with a value&nbsp;<em>greater than</em>&nbsp;X.</p>



<p>Return the number of&nbsp;<strong>good</strong>&nbsp;nodes in the binary tree.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [3,1,4,3,null,1,5]
<strong>Output:</strong> 4
<strong>Explanation:</strong> Nodes in blue are <strong>good</strong>.
Root Node (3) is always a good node.
Node 4 -&gt; (3,4) is the maximum value in the path starting from the root.
Node 5 -&gt; (3,4,5) is the maximum value in the path
Node 3 -&gt; (3,1,3) is the maximum value in the path.</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [3,3,null,4,2]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Node 2 -&gt; (3, 3, 2) is not good, because "3" is higher than it.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Root is considered as <strong>good</strong>.</pre>



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



<ul><li>The number of nodes in the binary tree is in the range&nbsp;<code>[1, 10^5]</code>.</li><li>Each node&#8217;s value is between&nbsp;<code>[-10^4, 10^4]</code>.</li></ul>



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



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int goodNodes(TreeNode* root, int max_val = INT_MIN) {
    if (!root) return 0;    
    return goodNodes(root-&gt;left, max(max_val, root-&gt;val))
           + goodNodes(root-&gt;right, max(max_val, root-&gt;val))
           + (root-&gt;val &gt;= max_val ? 1 : 0);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1448-count-good-nodes-in-binary-tree/">花花酱 LeetCode 1448. Count Good Nodes 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-1448-count-good-nodes-in-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1414-find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1414-find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 18 Apr 2020 18:31:10 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6632</guid>

					<description><![CDATA[<p>Given the number&#160;k,&#160;return the minimum number of Fibonacci numbers whose sum is equal to&#160;k, whether a Fibonacci number could be used multiple times. The Fibonacci&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1414-find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/">花花酱 LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K</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 number&nbsp;<code>k</code>,&nbsp;<em>return the minimum number of Fibonacci numbers whose sum is equal to&nbsp;</em><code>k</code>, whether a Fibonacci number could be used multiple times.</p>



<p>The Fibonacci numbers are defined as:</p>



<ul><li>F<sub>1</sub>&nbsp;= 1</li><li>F<sub>2</sub>&nbsp;= 1</li><li>F<sub>n</sub>&nbsp;= F<sub>n-1</sub>&nbsp;+ F<sub>n-2</sub>&nbsp;, for n &gt; 2.</li></ul>



<p>It is guaranteed that for the given constraints we can always find such fibonacci numbers that sum&nbsp;<code>k</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 7
<strong>Output:</strong> 2 
<strong>Explanation:</strong> The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... 
For k = 7 we can use 2 + 5 = 7.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 10
<strong>Output:</strong> 2 
<strong>Explanation:</strong> For k = 10 we can use 2 + 8 = 10.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 19
<strong>Output:</strong> 3 
<strong>Explanation:</strong> For k = 19 we can use 1 + 5 + 13 = 19.
</pre>



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



<ul><li><code>1 &lt;= k &lt;= 10^9</code></li></ul>



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



<p>Find the largest fibonacci numbers x that x &lt;= k, ans = 1 + find(k &#8211; x)</p>



<p>Time complexity: O(logk^2) -&gt; O(logk)<br>Space complexity: O(logk) -&gt; O(1)</p>



<p><strong>Recursive</strong></p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int findMinFibonacciNumbers(int k) {
    if (k == 0) return 0;
    int f1 = 1;
    int f2 = 1;    
    while (f2 &lt;= k) {
      swap(f1, f2);
      f2 += f1;
    }    
    return 1 + findMinFibonacciNumbers(k - f1);
  }
};</pre>
</div></div>



<p><strong>Iterative</strong></p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int findMinFibonacciNumbers(int k) {
    int f1 = 1;
    int f2 = 1;
    int ans = 1;
    while (f2 &lt;= k) {
      swap(f1, f2);
      f2 += f1;
    }    
    k -= f1;
    while (k) {
      if (k &gt;= f1) {
        k -= f1;
        ans += 1;
      }
      f2 -= f1;
      swap(f1, f2);      
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1414-find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/">花花酱 LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-1414-find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 14 Mar 2020 05:58:43 +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=6468</guid>

					<description><![CDATA[<p>Given two binary trees&#160;original&#160;and&#160;cloned&#160;and given a reference to a node&#160;target&#160;in the original tree. The&#160;cloned&#160;tree is a&#160;copy of&#160;the&#160;original&#160;tree. Return&#160;a reference to the same node&#160;in the&#160;cloned&#160;tree. Note&#160;that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/">花花酱 LeetCode 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given two binary trees&nbsp;<code>original</code>&nbsp;and&nbsp;<code>cloned</code>&nbsp;and given a reference to a node&nbsp;<code>target</code>&nbsp;in the original tree.</p>



<p>The&nbsp;<code>cloned</code>&nbsp;tree is a&nbsp;<strong>copy of</strong>&nbsp;the&nbsp;<code>original</code>&nbsp;tree.</p>



<p>Return&nbsp;<em>a reference to the same node</em>&nbsp;in the&nbsp;<code>cloned</code>&nbsp;tree.</p>



<p><strong>Note</strong>&nbsp;that you are&nbsp;<strong>not allowed</strong>&nbsp;to change any of the two trees or the&nbsp;<code>target</code>&nbsp;node and the answer&nbsp;<strong>must be</strong>&nbsp;a reference to a node in the&nbsp;<code>cloned</code>&nbsp;tree.</p>



<p><strong>Follow up:</strong>&nbsp;Solve the problem if repeated values on the tree are allowed.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/02/21/e1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tree = [7,4,3,null,null,6,19], target = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/02/21/e2.png" alt=""/></figure>



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



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/02/21/e3.png" alt=""/></figure>



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



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/02/21/e4.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tree = [1,2,3,4,5,6,7,8,9,10], target = 5
<strong>Output:</strong> 5
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/02/21/e5.png" alt=""/></figure>



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



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



<ul><li>The number of nodes in the&nbsp;<code>tree</code>&nbsp;is in the range&nbsp;<code>[1, 10^4]</code>.</li><li>The values of the nodes of the&nbsp;<code>tree</code>&nbsp;are unique.</li><li><code>target</code>&nbsp;node is a&nbsp;node from the&nbsp;<code>original</code>&nbsp;tree and is not&nbsp;<code>null</code>.</li></ul>



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



<p>Traverse both trees in the same order, if original == target, return cloned.</p>



<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:
  TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {
    if (!original) return nullptr;
    if (original == target) return cloned;
    auto l = getTargetCopy(original-&amp;gt;left, cloned-&amp;gt;left, target);
    auto r = getTargetCopy(original-&amp;gt;right, cloned-&amp;gt;right, target);
    return l ? l : r;
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -&amp;gt; TreeNode:
    if not original: return None
    if original == target: return cloned
    return self.getTargetCopy(original.left, cloned.left, target) or \
           self.getTargetCopy(original.right, cloned.right, target)</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/">花花酱 LeetCode 1379. Find a Corresponding Node of a Binary Tree in a Clone of That 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-1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 224. Basic Calculator</title>
		<link>https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/</link>
					<comments>https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/#comments</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 09 Mar 2020 20:33:55 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[calculator]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6438</guid>

					<description><![CDATA[<p>Implement a basic calculator to evaluate a simple expression string. The expression string may contain open&#160;(&#160;and closing parentheses&#160;), the plus&#160;+&#160;or minus sign&#160;-,&#160;non-negative&#160;integers and empty spaces&#160;.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/">花花酱 LeetCode 224. Basic Calculator</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 a basic calculator to evaluate a simple expression string.</p>



<p>The expression string may contain open&nbsp;<code>(</code>&nbsp;and closing parentheses&nbsp;<code>)</code>, the plus&nbsp;<code>+</code>&nbsp;or minus sign&nbsp;<code>-</code>,&nbsp;<strong>non-negative</strong>&nbsp;integers and empty spaces&nbsp;.</p>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> " 2-1 + 2 "
<strong>Output:</strong> 3</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> "(1+(4+5+2)-3)+(6+8)"
<strong>Output:</strong> 23</pre>



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



<ul><li>You may assume that the given expression is always valid.</li><li><strong>Do not</strong>&nbsp;use the&nbsp;<code>eval</code>&nbsp;built-in library function.</li></ul>



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



<p>Make a recursive call when there is an open parenthesis and return if there is close parenthesis.</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 calculate(string s) {    
    function&lt;int(int&amp;)&gt; eval = [&amp;](int&amp; pos) {
      int ret = 0;
      int sign = 1;
      int val = 0;
      while (pos &lt; s.size()) {
        const char ch = s[pos];
        if (isdigit(ch)) {
          val = val * 10 + (s[pos++] - '0');
        } else if (ch == '+' || ch == '-') {
          ret += sign * val;
          val = 0;
          sign = ch == '+' ? 1 : -1;
          ++pos;
        } else if (ch == '(') {
          val = eval(++pos);
        } else if (ch == ')') {          
          ++pos;
          break;
        } else {
          ++pos;
        }
      }
      return ret += sign * val;
    };
    int pos = 0;
    return eval(pos);
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def calculate(self, s: str) -&gt; int:
    self.pos = 0    
    def eval():
      val = 0
      sign = 1
      ret = 0
      while self.pos &lt; len(s):
        ch = s[self.pos]
        if ch == ' ':
          self.pos += 1
        elif ch == '(':
          self.pos += 1
          val = eval()
        elif ch == ')':
          self.pos += 1
          ret += sign * val
          return ret
        elif ch == '+' or ch == '-':
          ret += sign * val
          val = 0
          sign = 1 if ch == '+' else -1
          self.pos += 1
        else:
          val = val * 10 + (ord(ch) - ord('0'))
          self.pos += 1
      ret += val * sign
      return ret
    return eval()</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/recursion/leetcode-224-basic-calculator/">花花酱 LeetCode 224. Basic Calculator</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/recursion/leetcode-224-basic-calculator/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
