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

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

					<description><![CDATA[<p>You are given the&#160;root&#160;of a&#160;binary tree&#160;and an integer&#160;k. Return an integer denoting the size of the&#160;kth&#160;largest&#160;perfect binary&#160; subtree, or&#160;-1&#160;if it doesn&#8217;t exist. A&#160;perfect binary tree&#160;is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/">花花酱 LeetCode 3319. K-th Largest Perfect Subtree Size in Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given the&nbsp;<code>root</code>&nbsp;of a&nbsp;<strong>binary tree</strong>&nbsp;and an integer&nbsp;<code>k</code>.</p>



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



<pre class="crayon-plain-tag">class Solution {
public:
  int kthLargestPerfectSubtree(TreeNode* root, int k) {
    vector&amp;lt;int&gt; ss;
    function&amp;lt;int(TreeNode*)&gt; PerfectSubtree = &amp;#91;&amp;amp;](TreeNode* node) -&gt; int {
      if (node == nullptr) return 0;
      int l = PerfectSubtree(node-&gt;left);
      int r = PerfectSubtree(node-&gt;right);
      if (l == r &amp;amp;&amp;amp; l != -1) {
        ss.push_back(l + r + 1);
        return ss.back();
      }
      return -1;  
    };
    PerfectSubtree(root);
    sort(rbegin(ss), rend(ss));
    return k &amp;lt;= ss.size() ? ss&amp;#91;k - 1] : -1;
  }
};</pre>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/">花花酱 LeetCode 3319. K-th Largest Perfect Subtree Size in Binary Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1361. Validate Binary Tree Nodes</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-1361-validate-binary-tree-nodes/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-1361-validate-binary-tree-nodes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 23 Feb 2020 10:04:11 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[in-degree]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6370</guid>

					<description><![CDATA[<p>You have&#160;n&#160;binary tree nodes&#160;numbered from&#160;0&#160;to&#160;n - 1&#160;where node&#160;i&#160;has two children&#160;leftChild[i]&#160;and&#160;rightChild[i], return&#160;true&#160;if and only if&#160;all&#160;the given nodes form&#160;exactly one&#160;valid binary tree. If node&#160;i&#160;has no left child&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1361-validate-binary-tree-nodes/">花花酱 LeetCode 1361. Validate Binary 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[
<p>You have&nbsp;<code>n</code>&nbsp;binary tree nodes&nbsp;numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;where node&nbsp;<code>i</code>&nbsp;has two children&nbsp;<code>leftChild[i]</code>&nbsp;and&nbsp;<code>rightChild[i]</code>, return&nbsp;<code>true</code>&nbsp;if and only if&nbsp;<strong>all</strong>&nbsp;the given nodes form&nbsp;<strong>exactly one</strong>&nbsp;valid binary tree.</p>



<p>If node&nbsp;<code>i</code>&nbsp;has no left child then&nbsp;<code>leftChild[i]</code>&nbsp;will equal&nbsp;<code>-1</code>, similarly for the right child.</p>



<p>Note that the nodes have no values and that we only use the node numbers in this problem.</p>



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



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



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



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



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



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



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



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



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



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



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



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



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



<ul><li><code>1 &lt;= n &lt;= 10^4</code></li><li><code>leftChild.length == rightChild.length == n</code></li><li><code>-1 &lt;= leftChild[i], rightChild[i] &lt;= n - 1</code></li></ul>



<h2><strong>Solution: Count in-degrees for each node</strong></h2>



<p>in degree must &lt;= 1 and there must be exact one node that has 0 in-degree.</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:
  bool validateBinaryTreeNodes(int n, vector&lt;int&gt;&amp; leftChild, vector&lt;int&gt;&amp; rightChild) {
    vector&lt;int&gt; in(n);
    for (int l : leftChild) if (l &gt;= 0) ++in[l];
    for (int r : rightChild) if (r &gt;= 0) ++in[r];
    int zero = 0;
    for (int i = 0; i &lt; n; ++i) {
      if (in[i] &gt; 1) return false;
      if (in[i] == 0) ++zero;
    }
    // # of nodes without parent must be 1.
    return zero == 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-1361-validate-binary-tree-nodes/">花花酱 LeetCode 1361. Validate Binary 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-1361-validate-binary-tree-nodes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 337. House Robber III</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-337-house-robber-iii/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-337-house-robber-iii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 16 Mar 2018 05:18:31 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2105</guid>

					<description><![CDATA[<p>题目大意：给你一棵二叉树，不能同时取两个相邻的节点(parent/child)，问最多能取得的节点的值的和是多少。 Problem: https://leetcode.com/problems/house-robber-iii/description/ The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-337-house-robber-iii/">花花酱 LeetCode 337. House Robber III</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>题目大意：给你一棵二叉树，不能同时取两个相邻的节点(parent/child)，问最多能取得的节点的值的和是多少。</p>
<p><strong>Problem:</strong></p>
<p><a href="https://leetcode.com/problems/house-robber-iii/description/">https://leetcode.com/problems/house-robber-iii/description/</a></p>
<p>The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the &#8220;root.&#8221; Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that &#8220;all houses in this place forms a binary tree&#8221;. It will automatically contact the police if two directly-linked houses were broken into on the same night.</p>
<p>Determine the maximum amount of money the thief can rob tonight without alerting the police.</p>
<p><b>Example 1:</b></p>
<pre class="" crayon="false">     <span style="color: red;">3</span>
    / \
   2   3
    \   \ 
     <span style="color: red;">3   1</span>
</pre>
<p>Maximum amount of money the thief can rob = <span style="color: red;">3</span> + <span style="color: red;">3</span> + <span style="color: red;">1</span> = <b>7</b>.</p>
<p><b>Example 2:</b></p>
<pre class="crayon:false ">     3
    / \
   <span style="color: red;">4</span>   <span style="color: red;">5</span>
  / \   \ 
 1   3   1
</pre>
<p>Maximum amount of money the thief can rob = <span style="color: red;">4</span> + <span style="color: red;">5</span> = <b>9</b>.</p>
<p><strong>Idea: </strong></p>
<p>Compare grandparent + max of grandchildren(l.l + l.r + r.l + r.r) vs max of children (l + r)</p>
<p><b>Solution 1: Recursion w/o memorization </b></p>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 1289 ms
class Solution {
public:
  int rob(TreeNode* root) {
    if (root == nullptr) return 0;
    int val = root-&gt;val;
    int ll = root-&gt;left ? rob(root-&gt;left-&gt;left) : 0;
    int lr = root-&gt;left ? rob(root-&gt;left-&gt;right) : 0;
    int rl = root-&gt;right ? rob(root-&gt;right-&gt;left) : 0;
    int rr = root-&gt;right ? rob(root-&gt;right-&gt;right) : 0;
    return max(val + ll + lr + rl + rr, rob(root-&gt;left) + rob(root-&gt;right));
  }
};</pre><p><strong>Solution 2: </strong><b>Recursion w/ memorization </b></p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 15 ms
class Solution {
public:
  int rob(TreeNode* root) {
    if (root == nullptr) return 0;
    if (m_.count(root)) return m_[root];
    int val = root-&gt;val;
    int ll = root-&gt;left ? rob(root-&gt;left-&gt;left) : 0;
    int lr = root-&gt;left ? rob(root-&gt;left-&gt;right) : 0;
    int rl = root-&gt;right ? rob(root-&gt;right-&gt;left) : 0;
    int rr = root-&gt;right ? rob(root-&gt;right-&gt;right) : 0;
    return m_[root] = max(val + ll + lr + rl + rr, rob(root-&gt;left) + rob(root-&gt;right));
  }
private:
  unordered_map&lt;TreeNode*, int&gt; m_;
};</pre><p><strong>Solution 3: Recursion return children&#8217;s value</strong></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 10 ms (beats 97.57%)
class Solution {
public:
  int rob(TreeNode* root) {
    int l = 0;
    int r = 0;
    return rob(root, l, r);    
  }
private:
  // return rob(root) and stores rob(root-&gt;left/right) in l/r.
  int rob(TreeNode* root, int&amp; l, int&amp; r) {
    if (root == nullptr) return 0;
    int ll = 0;
    int lr = 0;
    int rl = 0;
    int rr = 0;
    l = rob(root-&gt;left, ll, lr);
    r = rob(root-&gt;right, rl, rr);    
    return max(root-&gt;val + ll + lr + rl + rr, l + r);
  }
};</pre><p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 64 ms (beats 93.18%)
"""
class Solution:
  def rob(self, root):
    def rob(root):
      if not root: return 0, 0, 0
      l, ll, lr = rob(root.left)
      r, rl, rr = rob(root.right)
      return max(root.val + ll + lr + rl + rr, l + r), l, r
    
    return rob(root)[0]</pre><p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-198-house-robber/">花花酱 LeetCode 198. House Robber</a></li>
</ul>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-337-house-robber-iii/">花花酱 LeetCode 337. House Robber III</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-337-house-robber-iii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 145. Binary Tree Postorder Traversal</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 08 Sep 2017 08:19:18 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[inorder]]></category>
		<category><![CDATA[iterative]]></category>
		<category><![CDATA[leetcode]]></category>
		<category><![CDATA[postorder]]></category>
		<category><![CDATA[preorder]]></category>
		<category><![CDATA[recursive]]></category>
		<category><![CDATA[solutions]]></category>
		<category><![CDATA[traversal]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=150</guid>

					<description><![CDATA[<p>Problem: Given a binary tree, return the postorder traversal of its nodes&#8217; values. For example: Given binary tree {1,#,2,3}, [crayon-67124b75841e7553759195/] return [3,2,1]. Note: Recursive solution is trivial, could you do&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/">花花酱 LeetCode 145. Binary Tree Postorder Traversal</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/A6iCX_5xiU4?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem:</strong></h1>
<p>Given a binary tree, return the <i>postorder</i> traversal of its nodes&#8217; values.</p>
<p>For example:<br />
Given binary tree <code>{1,#,2,3}</code>,</p><pre class="crayon-plain-tag">1
    \
     2
    /
   3</pre><p>return <code>[3,2,1]</code>.</p>
<p><b>Note:</b> Recursive solution is trivial, could you do it iteratively?</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1.png"><img class="alignnone size-full wp-image-154" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2.png"><img class="alignnone size-full wp-image-153" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/145-ep40-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<h1><strong>Solution 1:</strong></h1>
<p></p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    vector&lt;int&gt; postorderTraversal(TreeNode* root) {
        vector&lt;int&gt; ans;        
        postorderTraversal(root, ans);
        return ans;
    }
    
    void postorderTraversal(TreeNode* root, vector&lt;int&gt;&amp; ans) {
        if (!root) return;
        postorderTraversal(root-&gt;left, ans);
        postorderTraversal(root-&gt;right, ans);
        ans.push_back(root-&gt;val);
    }
};</pre><p></p>
<h1><strong>Solution 2:</strong></h1>
<p></p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    vector&lt;int&gt; postorderTraversal(TreeNode* root) {
        if (!root) return {};
        vector&lt;int&gt; ans;
        const vector&lt;int&gt; l = postorderTraversal(root-&gt;left);
        const vector&lt;int&gt; r = postorderTraversal(root-&gt;right);
        ans.insert(ans.end(), l.begin(), l.end());
        ans.insert(ans.end(), r.begin(), r.end());
        ans.push_back(root-&gt;val);
        return ans;
    }
};</pre><p></p>
<h1><strong>Solution 3:</strong></h1>
<p></p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    vector&lt;int&gt; postorderTraversal(TreeNode* root) {
        if (!root) return {};
        deque&lt;int&gt; ans;
        stack&lt;TreeNode*&gt; s;
        s.push(root);
        while (!s.empty()) {
            TreeNode* n = s.top();
            s.pop();
            ans.push_front(n-&gt;val); // O(1)
            if (n-&gt;left) s.push(n-&gt;left);
            if (n-&gt;right) s.push(n-&gt;right);
        }   
        return vector&lt;int&gt;(ans.begin(), ans.end());
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/">花花酱 LeetCode 145. Binary Tree Postorder Traversal</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-145-binary-tree-postorder-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 637. Average of Levels in Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-637-average-of-levels-in-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-637-average-of-levels-in-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 07 Sep 2017 09:18:40 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[DFS]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=142</guid>

					<description><![CDATA[<p>&#160; Problem: Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. Example 1:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-637-average-of-levels-in-binary-tree/">花花酱 LeetCode 637. Average of Levels 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><iframe width="500" height="375" src="https://www.youtube.com/embed/3VljCEnwcdU?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>&nbsp;</p>
<p><strong>Problem:</strong></p>
<p>Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">&lt;b&gt;Input:&lt;/b&gt;
    3
   / \
  9  20
    /  \
   15   7
&lt;b&gt;Output:&lt;/b&gt; [3, 14.5, 11]
&lt;b&gt;Explanation:&lt;/b&gt;
The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. 
Hence return [3, 14.5, 11].</pre><p>&nbsp;</p>
<p><strong>Time Complexity:</strong></p>
<p>O(n)</p>
<p><strong>Space Complexity:</strong></p>
<p>O(h)</p>
<p><strong>Solution 1:</strong></p>
<p>BFS</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    vector&lt;double&gt; averageOfLevels(TreeNode* root) {
        if(root == nullptr) return {};
        vector&lt;double&gt; ans;
        vector&lt;TreeNode*&gt; curr, next;
        curr.push_back(root);
        
        // process every level one by one
        while(!curr.empty()) {
            long long sum = 0;
            for(const auto&amp; node : curr) {
                sum += node-&gt;val;
                if (node-&gt;left) next.push_back(node-&gt;left);
                if (node-&gt;right) next.push_back(node-&gt;right);
            }
            
            ans.push_back(static_cast&lt;double&gt;(sum) / curr.size());
            
            curr.swap(next);
            next.clear();
        }
        
        return ans;
    }
};</pre><p><strong>Solution 2:</strong></p>
<p>DFS</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    vector&lt;double&gt; averageOfLevels(TreeNode* root) {
        if(root == nullptr) return {};
        vector&lt;pair&lt;long long, int&gt;&gt; sum_count;
        vector&lt;double&gt; ans;
        preorder(root, 0, sum_count);
        for(const auto&amp; p : sum_count)
            ans.push_back(static_cast&lt;double&gt;(p.first) / p.second);
        return ans;
    }
    
private:
    void preorder(TreeNode* root, int depth, vector&lt;pair&lt;long long, int&gt;&gt;&amp; sum_count) {
        if(root == nullptr) return;
        if(depth&gt;=sum_count.size()) sum_count.push_back({0,0});
        sum_count[depth].first += root-&gt;val;
        ++sum_count[depth].second;
        preorder(root-&gt;left, depth+1, sum_count);
        preorder(root-&gt;right, depth+1, sum_count);
    }
};</pre><p>&nbsp;</p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/">[解题报告] LeetCode 102. Binary Tree Level Order Traversal</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-637-average-of-levels-in-binary-tree/">花花酱 LeetCode 637. Average of Levels 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-637-average-of-levels-in-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 654. Maximum Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-654-maximum-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-654-maximum-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 05 Sep 2017 06:56:44 +0000</pubDate>
				<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[maximum]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=96</guid>

					<description><![CDATA[<p>&#160; Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-654-maximum-binary-tree/">花花酱 LeetCode 654. Maximum 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><iframe width="500" height="375" src="https://www.youtube.com/embed/oHnT9zTsXTg?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>&nbsp;</p>
<p>Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:</p>
<ol>
<li>The root is the maximum number in the array.</li>
<li>The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.</li>
<li>The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.</li>
</ol>
<p>Construct the maximum tree by the given array and output the root node of this tree.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1</pre><p><strong>Idea:</strong></p>
<p>Recursion</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/slide-654-1.png"><img class="alignnone size-full wp-image-97" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/slide-654-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/slide-654-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/slide-654-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/slide-654-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/slide-654-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Solution:</strong></p>
<p>With copy</p>
<p>Time complexity: O(nlogn) ~ O(n^2)</p>
<p>Space complexity: O(nlogn) ~ O(n^2)</p>
<p><span style="font-size: 1rem;">running time 79ms</span></p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:    
    TreeNode* constructMaximumBinaryTree(vector&lt;int&gt;&amp; nums) {
        if(nums.empty()) return nullptr;
        auto it = std::max_element(nums.begin(), nums.end());
        TreeNode* root=new TreeNode(*it);
        vector&lt;int&gt; left(nums.begin(), it);
        vector&lt;int&gt; right(it+1, nums.end());
        root-&gt;left = constructMaximumBinaryTree(left);
        root-&gt;right = constructMaximumBinaryTree(right);
        return root;
    }
}</pre><p>Without copy</p>
<p>Time complexity: O(nlogn) ~ O(n^2)</p>
<p>Space complexity: O(logn) ~ O(n)</p>
<p>running time 66ms</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:            
    TreeNode* constructMaximumBinaryTree(vector&lt;int&gt;&amp; nums) {
        return makeMBT(nums, 0, nums.size());
    }
private:
    TreeNode* makeMBT(const vector&lt;int&gt;&amp; nums, int begin, int end) {
        if(begin&gt;=end) return nullptr;
        auto it = std::max_element(nums.begin() + begin, nums.begin() + end);
        TreeNode* root=new TreeNode(*it);
        int index = it - nums.begin();
        root-&gt;left = makeMBT(nums, begin, index);
        root-&gt;right = makeMBT(nums, index+1, end);
        return root;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-654-maximum-binary-tree/">花花酱 LeetCode 654. Maximum 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/leetcode/leetcode-654-maximum-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 669. Trim a Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-669-trim-a-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-669-trim-a-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 05 Sep 2017 01:13:36 +0000</pubDate>
				<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[binary search tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[trim]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=90</guid>

					<description><![CDATA[<p>Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R &#62;= L).&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-669-trim-a-binary-search-tree/">花花酱 LeetCode 669. Trim a Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/L_t2x3nH61k?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>Given a binary search tree and the lowest and highest boundaries as <code>L</code> and <code>R</code>, trim the tree so that all its elements lies in <code>[L, R]</code> (R &gt;= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input:
    1
   / \
  0   2

  L = 1
  R = 2

Output: 
    1
      \
       2</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input:
    3
   / \
  0   4
   \
    2
   /
  1

  L = 1
  R = 3

Output:
      3
     / 
   2   
  /
 1</pre><p>This problem can be solved with recursion</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1.png"><img class="alignnone wp-image-100 size-full" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/699-1-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>There 3 cases in total depends on the root value and L, R</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>Solution:</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
    // No cleanup -&gt; memory leak 
    TreeNode* trimBST(TreeNode* root, int L, int R) {
        if(!root) return nullptr;
        // val not in range, return the left/right subtrees
        if(root-&gt;val &lt; L) return trimBST(root-&gt;right, L, R);
        if(root-&gt;val &gt; R) return trimBST(root-&gt;left, L, R);
        // val in [L, R], recusively trim left/right subtrees
        root-&gt;left = trimBST(root-&gt;left, L, R);
        root-&gt;right = trimBST(root-&gt;right, L, R);
        return root;
    }
};</pre><p>The previous solution has potential memory leak for languages without garbage collection.</p>
<p>Here&#8217;s the full program to delete trimmed nodes.</p><pre class="crayon-plain-tag">// Author: Huahua
#include &lt;iostream&gt;
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
 
class Solution {
public:
    
    // With cleanup -&gt; no memory leak
    TreeNode*&amp; trimBST(TreeNode*&amp; root, int L, int R) {
        if(!root) return root;
        
        if(root-&gt;val &lt; L) {            
            auto&amp; result = trimBST(root-&gt;right, L, R);
            deleteTree(root-&gt;left);
            delete root;
            root=nullptr;
            return result;
        } else if(root-&gt;val &gt; R) {
            auto&amp; result = trimBST(root-&gt;left, L, R);
            deleteTree(root-&gt;right);
            delete root;
            root=nullptr;
            return result;
        } else {
            // recusively trim left/right subtrees
            root-&gt;left = trimBST(root-&gt;left, L, R);
            root-&gt;right = trimBST(root-&gt;right, L, R);
            return root;
        }
    }
    
    void deleteTree(TreeNode* &amp;root) {
        if(!root) return;
        deleteTree(root-&gt;left);
        deleteTree(root-&gt;right);
        delete root;
        root=nullptr;
    }
};

void PrintTree(TreeNode* root) {
    if(!root) {
        cout&lt;&lt;"null ";
        return;
    };
    if(!root-&gt;left &amp;&amp; !root-&gt;right) {
        cout&lt;&lt;root-&gt;val&lt;&lt;" ";
    } else {
        cout&lt;&lt;root-&gt;val&lt;&lt;" ";
        PrintTree(root-&gt;left);
        PrintTree(root-&gt;right);
    }
}


int main()
{
    TreeNode* root=new TreeNode(2);
    root-&gt;left=new TreeNode(1);
    root-&gt;right=new TreeNode(3);
    PrintTree(root);
    std::cout&lt;&lt;std::endl;
    
    TreeNode* t = Solution().trimBST(root, 3, 4);
    PrintTree(t);
    std::cout&lt;&lt;std::endl;

    // Original root was deleted
    PrintTree(root);
    std::cout&lt;&lt;std::endl;
    
    return 0;
}</pre><p>Example output</p><pre class="crayon-plain-tag">2 1 3 
3 
null</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-669-trim-a-binary-search-tree/">花花酱 LeetCode 669. Trim a Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/leetcode/leetcode-669-trim-a-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 102. Binary Tree Level Order Traversal</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 04 Sep 2017 07:53:41 +0000</pubDate>
				<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[traversal]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=69</guid>

					<description><![CDATA[<p>Given a binary tree, return the level order traversal of its nodes&#8217; values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], [crayon-67124b75851e0859518247/]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/">花花酱 LeetCode 102. Binary Tree Level Order Traversal</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/Tuij96VBdu8?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p>Given a binary tree, return the <i>level order</i> traversal of its nodes&#8217; values. (ie, from left to right, level by level).</p>
<p>For example:<br />
Given binary tree <code>[3,9,20,null,null,15,7]</code>,</p><pre class="crayon-plain-tag">3
   / \
  9  20
    /  \
   15   7</pre><p>return its level order traversal as:</p><pre class="crayon-plain-tag">[
  [3],
  [9,20],
  [15,7]
]</pre><p>Solution 1: BFS O(n)</p><pre class="crayon-plain-tag">class Solution {
public:
    vector&lt;vector&lt;int&gt;&gt; levelOrder(TreeNode* root) {
        if(!root) return {};
        vector&lt;vector&lt;int&gt;&gt; ans;
        vector&lt;TreeNode*&gt; curr,next;
        curr.push_back(root);
        while(!curr.empty()) {
            ans.push_back({});
            for(TreeNode* node : curr) {
                ans.back().push_back(node-&gt;val);
                if(node-&gt;left) next.push_back(node-&gt;left);
                if(node-&gt;right) next.push_back(node-&gt;right);
            }
            curr.swap(next);
            next.clear();
        }
        return ans;
    }
};</pre><p>Solution 2: DFS O(n)</p><pre class="crayon-plain-tag">class Solution {
public:
    vector&lt;vector&lt;int&gt;&gt; levelOrder(TreeNode* root) {
        vector&lt;vector&lt;int&gt;&gt; ans;
        DFS(root, 0 /* depth */, ans);
        return ans;
    }
private:
    void DFS(TreeNode* root, int depth, vector&lt;vector&lt;int&gt;&gt;&amp; ans) {
        if(!root) return;
        // Works with pre/in/post order
        while(ans.size()&lt;=depth) ans.push_back({});
        ans[depth].push_back(root-&gt;val); // pre-order
        DFS(root-&gt;left, depth+1, ans);        
        DFS(root-&gt;right, depth+1, ans);   
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-102-binary-tree-level-order-traversal/">花花酱 LeetCode 102. Binary Tree Level Order Traversal</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/leetcode/leetcode-102-binary-tree-level-order-traversal/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 110. Balanced Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-110-balanced-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-110-balanced-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Sep 2017 09:57:03 +0000</pubDate>
				<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=55</guid>

					<description><![CDATA[<p>Solution 1: O(nlogn) [crayon-67124b7585627099167800/] Solution 2: O(n) [crayon-67124b758562c807769233/] Java [crayon-67124b758562e364497906/] &#160; Python [crayon-67124b7585630224123457/] &#160;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-110-balanced-binary-tree/">花花酱 LeetCode 110. Balanced 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><iframe width="500" height="375" src="https://www.youtube.com/embed/C75oWiy0bWM?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>Solution 1: O(nlogn)</p><pre class="crayon-plain-tag">// Author: Huahua
// O(nlogn)
class Solution {
Solution 1: O(nlogn)
public:
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        int left_height = height(root-&gt;left);
        int right_height = height(root-&gt;right);
        return (abs(left_height - right_height)&lt;=1) &amp;&amp; isBalanced(root-&gt;left) &amp;&amp; isBalanced(root-&gt;right);
    }
private:
    int height(TreeNode* root) {
        if(!root) return 0;
        return max(height(root-&gt;left), height(root-&gt;right))+1;
    }
};</pre><p>Solution 2: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// O(n)
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(!root) return true;
        bool balanced = true;
        height(root, &amp;balanced);
        return balanced;
    }
private:
    int height(TreeNode* root, bool* balanced) {
        if(!root) return 0;
        int left_height = height(root-&gt;left, balanced);
        if(!balanced) return -1;
        int right_height = height(root-&gt;right, balanced);
        if(!balanced) return -1;
        if(abs(left_height-right_height)&gt;1) {
            *balanced = false;
            return -1;
        }
        return max(left_height, right_height) + 1;
    }
};</pre><p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 1 ms
class Solution {
  private boolean balanced;
  
  private int height(TreeNode root) {
    if (root == null || !this.balanced) return -1;
    int l = height(root.left);
    int r = height(root.right);
    if (Math.abs(l - r) &gt; 1) {
      this.balanced = false;
      return -1;
    }
    return Math.max(l, r) + 1;
  }
  
  public boolean isBalanced(TreeNode root) {
    this.balanced = true;
    height(root);
    return this.balanced;
  }
}</pre><p>&nbsp;</p>
<p>Python</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 76 ms
"""
class Solution:
  def isBalanced(self, root):
    self.balanced = True
    def height(root):
      if not root or not self.balanced: return -1
      l = height(root.left)
      r = height(root.right)
      if abs(l - r) &gt; 1:
        self.balanced = False
        return -1
      return max(l, r) + 1
    height(root)
    return self.balanced</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-110-balanced-binary-tree/">花花酱 LeetCode 110. Balanced 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/leetcode/leetcode-110-balanced-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
