<?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>path sum Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/path-sum/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/path-sum/</link>
	<description></description>
	<lastBuildDate>Tue, 18 Sep 2018 15:40:48 +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>path sum Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/path-sum/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 112. Path Sum</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-112-path-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-112-path-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 25 Aug 2018 15:41:07 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[path sum]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3691</guid>

					<description><![CDATA[<p>Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-112-path-sum/">花花酱 LeetCode 112. Path Sum</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/zdClzfnkvDY?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1>Problem</h1>
<p>Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.</p>
<p><strong>Note:</strong> A leaf is a node with no children.</p>
<p><strong>Example:</strong></p>
<p>Given the below binary tree and <code>sum = 22</code>,</p>
<pre class="crayon:false">      <strong>5</strong>
     <strong>/</strong> \
    <strong>4</strong>   8
   <strong>/</strong>   / \
  <strong>11</strong>  13  4
 /  <strong>\</strong>      \
7    <strong>2</strong>      1
</pre>
<p>return true, as there exist a root-to-leaf path <code>5-&gt;4-&gt;11-&gt;2</code> which sum is 22.</p>
<p>&nbsp;</p>
<h1>Solution: Recursion</h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  bool hasPathSum(TreeNode* root, int sum) {
    if (!root) return false;
    if (!root-&gt;left &amp;&amp; !root-&gt;right) return root-&gt;val==sum;
    int new_sum = sum - root-&gt;val;
    return hasPathSum(root-&gt;left, new_sum) || hasPathSum(root-&gt;right, new_sum);
  }
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/tree/leetcode-113-path-sum-ii/">花花酱 LeetCode 113. Path Sum II</a></li>
<li><a href="https://zxi.mytechroad.com/blog/tree/leetcode-437-path-sum-iii/">花花酱 LeetCode 437. Path Sum III</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-112-path-sum/">花花酱 LeetCode 112. Path Sum</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-112-path-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 437. Path Sum III</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-437-path-sum-iii/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-437-path-sum-iii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 24 Mar 2018 09:05:30 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[path sum]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2332</guid>

					<description><![CDATA[<p>Problem 题目大意：给你一棵二叉树，返回单向的路径和等于sum的路径数量。 https://leetcode.com/problems/path-sum-iii/description/ You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-437-path-sum-iii/">花花酱 LeetCode 437. Path Sum 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[<h1><strong>Problem</strong></h1>
<p>题目大意：给你一棵二叉树，返回单向的路径和等于sum的路径数量。</p>
<p><a href="https://leetcode.com/problems/path-sum-iii/description/">https://leetcode.com/problems/path-sum-iii/description/</a></p>
<p>You are given a binary tree in which each node contains an integer value.</p>
<p>Find the number of paths that sum to a given value.</p>
<p>The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).</p>
<p>The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.</p>
<h2><b>Example:</b></h2>
<pre class="crayon:false">root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    <b>5</b>   <b>-3</b>
   <b>/</b> <b>\</b>    <b>\</b>
  <b>3</b>   <b>2</b>   <b>11</b>
 / \   <b>\</b>
3  -2   <b>1</b>

Return 3. The paths that sum to 8 are:

1.  5 -&gt; 3
2.  5 -&gt; 2 -&gt; 1
3. -3 -&gt; 11</pre>
<h1>Solution 1<strong>: Recursion</strong></h1>
<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: 21 ms
class Solution {
public:
  int pathSum(TreeNode* root, int sum) {
    if (!root) return 0;
    return numberOfPaths(root, sum) + pathSum(root-&gt;left, sum) + pathSum(root-&gt;right, sum);
  }
private:
  int numberOfPaths(TreeNode* root, int left) {
    if (!root) return 0;    
    left -= root-&gt;val;
    return (left == 0 ? 1 : 0) + numberOfPaths(root-&gt;left, left) + numberOfPaths(root-&gt;right, left);
  }
};</pre><p></p>
<h1><strong>Solution 2: Running Prefix Sum</strong></h1>
<p>Same idea to <a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-560-subarray-sum-equals-k/">花花酱 LeetCode 560. Subarray Sum Equals K</a></p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(h)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 13 ms (beats 97.74%)
public:
  int pathSum(TreeNode* root, int sum) {
    ans_ = 0;
    sums_ = {{0, 1}};
    pathSum(root, 0, sum);
    return ans_;
  }
private:
  int ans_;
  unordered_map&lt;int, int&gt; sums_;
  
  void pathSum(TreeNode* root, int cur, int sum) {
    if (!root) return;
    cur += root-&gt;val;
    ans_ += sums_[cur - sum];
    ++sums_[cur];
    pathSum(root-&gt;left, cur, sum);
    pathSum(root-&gt;right, cur, sum);
    --sums_[cur];
  }
};</pre><p></p>
<h1><strong>Related Problem</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-560-subarray-sum-equals-k/">花花酱 LeetCode 560. Subarray Sum Equals K</a></li>
</ul>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-437-path-sum-iii/">花花酱 LeetCode 437. Path Sum 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-437-path-sum-iii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 741. Cherry Pickup</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-741-cherry-pickup/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-741-cherry-pickup/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 05 Dec 2017 00:47:48 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[path sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1098</guid>

					<description><![CDATA[<p>题目大意：给你樱桃田的地图（1: 樱桃, 0: 空, -1: 障碍物）。然你从左上角走到右下角（只能往右或往下），再从右下角走回左上角（只能往左或者往上）。问你最多能采到多少棵樱桃。 Problem: In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-741-cherry-pickup/">花花酱 LeetCode 741. Cherry Pickup</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/vvPSWORCKow?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你樱桃田的地图（1: 樱桃, 0: 空, -1: 障碍物）。然你从左上角走到右下角（只能往右或往下），再从右下角走回左上角（只能往左或者往上）。问你最多能采到多少棵樱桃。</p>
<p><strong>Problem:</strong></p>
<p>In a N x N <code>grid</code> representing a field of cherries, each cell is one of three possible integers.</p>
<ul>
<li>0 means the cell is empty, so you can pass through;</li>
<li>1 means the cell contains a cherry, that you can pick up and pass through;</li>
<li>-1 means the cell contains a thorn that blocks your way.</li>
</ul>
<p>Your task is to collect maximum number of cherries possible by following the rules below:</p>
<ul>
<li>Starting at the position (0, 0) and reaching (N-1, N-1) by moving right or down through valid path cells (cells with value 0 or 1);</li>
<li>After reaching (N-1, N-1), returning to (0, 0) by moving left or up through valid path cells;</li>
<li>When passing through a path cell containing a cherry, you pick it up and the cell becomes an empty cell (0);</li>
<li>If there is no valid path between (0, 0) and (N-1, N-1), then no cherries can be collected.</li>
</ul>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: grid =
[[0, 1, -1],
 [1, 0, -1],
 [1, 1,  1]]
Output: 5
Explanation: 
The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.</pre><p><b>Note:</b></p>
<ul>
<li><code>grid</code> is an <code>N</code> by <code>N</code> 2D array, with <code>1 &lt;= N &lt;= 50</code>.</li>
<li>Each <code>grid[i][j]</code> is an integer in the set <code>{-1, 0, 1}</code>.</li>
<li>It is guaranteed that grid[0][0] and grid[N-1][N-1] are not -1.</li>
</ul>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea</strong>:</p>
<p>DP</p>
<p><span style="font-weight: 400;">Key observation: (0,0) to (n-1, n-1) to (0, 0) is the same as (n-1,n-1) to (0,0) twice</span></p>
<ol>
<li style="font-weight: 400;"><span style="font-weight: 400;">Two people starting from (n-1, n-1) and go to (0, 0). </span></li>
<li style="font-weight: 400;"><span style="font-weight: 400;">They move one step (left or up) at a time simultaneously. And pick up the cherry within the grid (if there is one).</span></li>
<li style="font-weight: 400;"><span style="font-weight: 400;">if they ended up at the same grid with a cherry. Only one of them can pick up it.</span></li>
</ol>
<p><span style="font-weight: 400;">Solution: DP / Recursion with memoization. </span></p>
<p><span style="font-weight: 400;">x1, y1, x2 to represent a state y2 can be computed: y2 = x1 + y1 &#8211; x2</span></p>
<p><span style="font-weight: 400;">dp(x1, y1, x2) computes the max cherries if start from {(x1, y1), (x2, y2)} to (0, 0), which is a recursive function.</span></p>
<p>Since two people move independently, there are 4 subproblems: (left, left), (left, up), (up, left), (left, up). Finally, we have:</p>
<p><span style="font-weight: 400;">dp(x1, y1, x2)= g[y1][x1] + g[y2][x2] + max{dp(x1-1,y1,x2-1), </span><span style="font-weight: 400;">dp(x1,y1-1,x2-1), dp(x1-1,y1,x2), dp(x1,y1-1,x2)</span><span style="font-weight: 400;">}</span></p>
<p><span style="font-weight: 400;">Time complexity: O(n^</span><span style="font-weight: 400;">3</span><span style="font-weight: 400;">) </span></p>
<p><span style="font-weight: 400;">Space complexity: O(n^</span><span style="font-weight: 400;">3</span><span style="font-weight: 400;">)</span></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/741-ep123.png"><img class="alignnone size-full wp-image-1102" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/741-ep123.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/741-ep123.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/741-ep123-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/741-ep123-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<h1><strong>Solution: DP</strong></h1>
<p>Time complexity: O(n^3)</p>
<p>Space complexity: O(n^3)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C ++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 32 ms
class Solution {
public:
    int cherryPickup(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {
        const int n = grid.size();
        grid_ = &amp;grid;
        m_ = vector&lt;vector&lt;vector&lt;int&gt;&gt;&gt;(
                n, vector&lt;vector&lt;int&gt;&gt;(n, vector&lt;int&gt;(n, INT_MIN)));
        return max(0, dp(n - 1, n - 1, n - 1));
    }
private:
    // max cherries from (x1, y1) to (0, 0) + (x2, y2) to (0, 0)
    int dp(int x1, int y1, int x2) {
        const int y2 = x1 + y1 - x2;
        if (x1 &lt; 0 || y1 &lt; 0 || x2 &lt; 0 || y2 &lt; 0) return -1;
        if ((*grid_)[y1][x1] &lt; 0 || (*grid_)[y2][x2] &lt; 0) return -1;
        if (x1 == 0 &amp;&amp; y1 == 0) return (*grid_)[y1][x1];
        if (m_[x1][y1][x2] != INT_MIN) return m_[x1][y1][x2];        
        int ans =  max(max(dp(x1 - 1, y1, x2 - 1), dp(x1, y1 - 1, x2)),
                       max(dp(x1, y1 - 1, x2 - 1), dp(x1 - 1, y1, x2)));
        if (ans &lt; 0) return m_[x1][y1][x2] = -1;
        ans += (*grid_)[y1][x1];
        if (x1 != x2) ans += (*grid_)[y2][x2];
        
        return m_[x1][y1][x2] = ans;
    }
    
    vector&lt;vector&lt;vector&lt;int&gt;&gt;&gt; m_;
    vector&lt;vector&lt;int&gt;&gt;* grid_; // does not own the object
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  private int[][] grid;
  private int[][][] memo;  
  public int cherryPickup(int[][] grid) {
    this.grid = grid;
    int m = grid.length;
    int n = grid[0].length;
    memo = new int[m][n][n];
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j)
        Arrays.fill(memo[i][j], Integer.MIN_VALUE);
    return Math.max(0, dp(n - 1, m - 1, n - 1));
  }
  
  private int dp(int x1, int y1, int x2) {
    final int y2 = x1 + y1 - x2;
    if (x1 &lt; 0 || y1 &lt; 0 || x2 &lt; 0 || y2 &lt; 0) return -1;
    if (grid[y1][x1] &lt; 0 || grid[y2][x2] &lt; 0) return -1;
    if (x1 == 0 &amp;&amp; y1 == 0) return grid[y1][x1];
    if (memo[y1][x1][x2] != Integer.MIN_VALUE) return memo[y1][x1][x2];
    memo[y1][x1][x2] = Math.max(Math.max(dp(x1 - 1, y1, x2 - 1), dp(x1, y1 - 1, x2)),
                                Math.max(dp(x1, y1 - 1, x2 - 1), dp(x1 - 1, y1, x2)));
    
    if (memo[y1][x1][x2] &gt;= 0) {
      memo[y1][x1][x2] += grid[y1][x1];
      if (x1 != x2) memo[y1][x1][x2] += grid[y2][x2];
    }
    
    return memo[y1][x1][x2];
  }
}</pre><p>&nbsp;</p>
</div></div>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-64-minimum-path-sum/">[解题报告] LeetCode 64. Minimum Path Sum</a></li>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-63-unique-paths-ii/">[解题报告] LeetCode 63. Unique Paths II</a></li>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-62-unique-paths/">[解题报告] LeetCode 62. Unique Paths</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-741-cherry-pickup/">花花酱 LeetCode 741. Cherry Pickup</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/dynamic-programming/leetcode-741-cherry-pickup/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 113. Path Sum II</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-113-path-sum-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-113-path-sum-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 28 Nov 2017 05:14:24 +0000</pubDate>
				<category><![CDATA[Medium]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[path sum]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=952</guid>

					<description><![CDATA[<p>Problem: Given a binary tree and a sum, find all root-to-leaf paths where each path&#8217;s sum equals the given sum. For example: Given the below&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-113-path-sum-ii/">花花酱 LeetCode 113. Path Sum II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/zrN2dxtQ0f0?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<div class="question-description">
<p>Given a binary tree and a sum, find all root-to-leaf paths where each path&#8217;s sum equals the given sum.</p>
<p>For example:<br />
Given the below binary tree and <code>sum = 22</code>,</p><pre class="crayon-plain-tag">5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1</pre><p>return</p><pre class="crayon-plain-tag">[
   [5,4,11,2],
   [5,8,4,5]
]</pre><p>
</div>
<div id="interviewed-div"><strong>Idea:</strong></div>
<div>Recursion</div>
<div></div>
<div><strong>Solution:</strong></div>
<div>C++</div>
<div></div>
<div>
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 9 ms
class Solution {
public:
    vector&lt;vector&lt;int&gt;&gt; pathSum(TreeNode* root, int sum) {
        vector&lt;vector&lt;int&gt;&gt; ans;
        vector&lt;int&gt; curr;
        pathSum(root, sum, curr, ans);
        return ans;
    }
private:
    void pathSum(TreeNode* root, int sum, vector&lt;int&gt;&amp; curr, vector&lt;vector&lt;int&gt;&gt;&amp; ans) {
        if(root==nullptr) return;
        if(root-&gt;left==nullptr &amp;&amp; root-&gt;right==nullptr) {
            if(root-&gt;val == sum) {
                ans.push_back(curr);
                ans.back().push_back(root-&gt;val);
            }
            return;
        }
        
        curr.push_back(root-&gt;val);
        int new_sum = sum - root-&gt;val;
        pathSum(root-&gt;left, new_sum, curr, ans);
        pathSum(root-&gt;right, new_sum, curr, ans);
        curr.pop_back();
    }
};</pre><p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-124-binary-tree-maximum-path-sum/">LeetCode 124. Binary Tree Maximum Path Sum</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-543-diameter-of-binary-tree/">[解题报告] LeetCode 543. Diameter of Binary Tree</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-687-longest-univalue-path/">[解题报告] LeetCode 687. Longest Univalue Path</a></li>
<li></li>
</ul>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-113-path-sum-ii/">花花酱 LeetCode 113. Path Sum II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-113-path-sum-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 124. Binary Tree Maximum Path Sum</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-124-binary-tree-maximum-path-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-124-binary-tree-maximum-path-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 18 Oct 2017 02:10:04 +0000</pubDate>
				<category><![CDATA[Hard]]></category>
		<category><![CDATA[Tree]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[path sum]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=622</guid>

					<description><![CDATA[<p>Problem: Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-124-binary-tree-maximum-path-sum/">花花酱 LeetCode 124. Binary Tree Maximum Path Sum</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/9ZNky1wqNUw?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given a binary tree, find the maximum path sum.</p>
<p>For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain <b>at least one node</b> and does not need to go through the root.</p>
<p>For example:<br />
Given the below binary tree,</p><pre class="crayon-plain-tag">1
      / \
     2   3</pre><p>Return <code>6</code>.</p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Recursion</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/124-ep90-1.png"><img class="alignnone size-full wp-image-626" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/124-ep90-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/124-ep90-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/124-ep90-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/124-ep90-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/124-ep90-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>Time complexity O(n)</p>
<p>Space complexity O(h)</p>
<h1><strong>Solution: Recursion</strong></h1>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 19 ms
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        if (!root) return 0;
        int ans = INT_MIN;
        maxPathSum(root, ans);
        return ans;
    }
private:
    int maxPathSum(TreeNode* root, int&amp; ans) {
        if (!root) return 0;
        int l = max(0, maxPathSum(root-&gt;left, ans));
        int r = max(0, maxPathSum(root-&gt;right, ans));
        int sum = l + r + root-&gt;val;
        ans = max(ans, sum);
        return max(l, r) + root-&gt;val;
    }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 138 ms (&lt; 90.38%)
"""
class Solution(object):
    def _maxPathSum(self, root):
        if not root: return -sys.maxint
        l = max(0, self._maxPathSum(root.left))
        r = max(0, self._maxPathSum(root.right))
        self.ans = max(self.ans, root.val + l + r)
        return root.val + max(l, r)
        
    def maxPathSum(self, root):
        self.ans = -sys.maxint
        self._maxPathSum(root)
        return self.ans</pre><p></div></div></p>
<p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-687-longest-univalue-path/">[解题报告] LeetCode 687. Longest Univalue Path</a></li>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-543-diameter-of-binary-tree/">[解题报告] LeetCode 543. Diameter of Binary Tree</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-124-binary-tree-maximum-path-sum/">花花酱 LeetCode 124. Binary Tree Maximum Path Sum</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-124-binary-tree-maximum-path-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
