add 124. Binary Tree Maximum Path Sum 🍺

This commit is contained in:
ShusenTang 2020-03-04 16:07:11 +08:00
parent 6f7fef12cc
commit 519b590852
2 changed files with 37 additions and 0 deletions

View File

@ -116,6 +116,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。
| 121 |[Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/121.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock.md)|Easy| |
| 122 |[Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/122.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock%20II.md)|Easy| |
| 123 |[Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/123.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock%20III.md)|Hard| |
| 124 |[Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)|[C++](solutions/124.%20Binary%20Tree%20Maximum%20Path%20Sum.md)|Hard| |
| 125 |[Valid Palindrome](https://leetcode.com/problems/valid-palindrome)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/125.%20Valid%20Palindrome.md)|Easy| |
| 127 |[Word Ladder](https://leetcode.com/problems/word-ladder/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/127.%20Word%20Ladder.md)|Medium| |
| 129 |[Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/129.%20Sum%20Root%20to%20Leaf%20Numbers.md)|Medium| |

View File

@ -0,0 +1,36 @@
# [124. Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)
# 思路
给定一棵二叉树,求最大路径和,路径的起始和结尾可以是任意节点。
这题的难点就在于起始点和结尾点都可以是任意节点,如果要求起始点就是根节点那就好做很多。我们设`maxRootPathSum(root)`代表以`root`为起始结点的路径最大和,那题目要求的`maxPathSum(root)`是候选值可能是多少呢?很简单,我们可以计算`root`左右两个子结点的`maxRootPathSum`,那么`maxPathSum(root)`就可能等于`root->val + maxPathSum(root->left) + maxPathSum(root->right)`。所以我们可以用一个类似后序遍历的递归函数来实现`maxPathSum(root)`在这个递归函数中用一个全局变量res记录遇到的最大的`maxPathSum`。
> 总结:由于二叉树本来就是通过递归定义的,所以二叉树的题很多可以用递归来做,而且多数时候就是类似遍历一遍二叉树。
相当于就是后序遍历所以复杂度为O(n)。
# C++
``` C++
class Solution {
private:
int res = INT_MIN;
int maxRootPathSum(TreeNode* root){
/*
以root为起始结点的路径最大和
*/
if(!root) return 0;
int l = max(maxRootPathSum(root -> left), 0);
int r = max(maxRootPathSum(root -> right), 0);
res = max(res, root -> val + l + r);
return root -> val + max(l, r);
}
public:
int maxPathSum(TreeNode* root) {
maxRootPathSum(root);
return res;
}
};
```