Leetcode - Binary Tree Maximum Path Sum
来源:互联网 发布:linux 给用户root权限 编辑:程序博客网 时间:2024/06/05 16:00
解题的关键在于这条路径只能是先往上走,到达某个最高点,再往下走,换句话说,只能有一次转折的机会。所以递归这棵树,记录以某个子节点为转折点时的最大值。值得注意的是树节点的值有负值,所以如果某个子路径的和小于0,放弃它(设置和为0)。
class Solution {public:int maxPathSum(TreeNode *root) {int maxSum = -1 << 30;int leftMax = pathMaxSum(root->left, maxSum);if (leftMax < 0)leftMax = 0;int rightMax = pathMaxSum(root->right, maxSum);if (rightMax < 0)rightMax = 0;int pathSum = leftMax + rightMax + root->val;if (pathSum > maxSum)return pathSum;elsereturn maxSum;}int pathMaxSum(TreeNode* node, int& maxSum){if (node == NULL)return 0;int leftMax = pathMaxSum(node->left, maxSum);if (leftMax < 0)leftMax = 0;int rightMax = pathMaxSum(node->right, maxSum);if (rightMax < 0)rightMax = 0;if (leftMax + rightMax + node->val > maxSum)//turn down at this pointmaxSum = leftMax + rightMax + node->val;int pathMax = leftMax > rightMax ? leftMax : rightMax;pathMax += node->val;return pathMax;}};
0 0
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 【Leetcode】Binary Tree Maximum Path Sum
- LeetCode | Binary Tree Maximum Path Sum
- Android性能测试工具之APT
- IP:网际协议
- Android中实现ExpandableListView即下拉的listview
- ArcGIS Engine中空间参照(地理坐标)相关方法总结
- Integer对象比较
- Leetcode - Binary Tree Maximum Path Sum
- 扩展视频连接使用光纤光学
- 您是否正在寻找事件管理悉尼,那么你来对地方了
- 快速的APK设备易于免费的Android应用软件,而无需编码技巧
- Using NUnit to Execute Selenium WebDriver Tests
- 快速的APK厂商快速和免费的Android应用软件,而无需编码技巧
- 快速的APK厂商快速和免费的Android应用程序生成器无需编码技巧
- 快速的APK制作简易免费的Android应用软件,而无需编码技巧
- 我的专业学的是网络工程 学的编程语言是C# 以后搞什么方向啊