[leetcode] 124. Binary Tree Maximum Path Sum
来源:互联网 发布:阿佳妮 知乎 编辑:程序博客网 时间:2024/05/16 05:36
Given a binary tree, find the maximum path sum.
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 does not need to go through the root.
For example:
Given the below binary tree,
1
/ \ 2 3
Return6.
这道题是计算二叉树最大路径和,题目难度为Hard。
基于二叉树数据结构的特性,我们知道最大路径和的路径肯定存在一个自己的根节点,它的左右子树(形似链表)即是路径的左右两部分,这点需要大家首先确认。这样我们以每个节点作为此根节点,分别计算从它的左右子树开始的最大路径和,之后加上此根节点值即是此根节点确定的最大路径和。这里需要注意如果左右子树的最大路径和是负数,则抛弃这个子树的路径,因为加上它会使路径和变小,把这个子树的路径和记为0即可。这样深度优先遍历二叉树即可比较获得最大路径和。具体代码:
class Solution { int getMaxPathSum(TreeNode* root, int& maxSum) { if(!root) return 0; int left = max(getMaxPathSum(root->left, maxSum), 0); int right = max(getMaxPathSum(root->right, maxSum), 0); maxSum = max(maxSum, left+right+root->val); return max(left, right) + root->val; }public: int maxPathSum(TreeNode* root) { if(!root) return 0; int maxSum = INT_MIN; getMaxPathSum(root, maxSum); return maxSum; }};
0 0
- LeetCode 124. Binary Tree Maximum Path Sum
- [LeetCode]*124.Binary Tree Maximum Path Sum
- [Leetcode] 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- [leetcode] 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- [LeetCode] 124. Binary Tree Maximum Path Sum
- leetcode 124.Binary Tree Maximum Path Sum
- leetcode-124. Binary Tree Maximum Path Sum
- [LeetCode]124. Binary Tree Maximum Path Sum
- Leetcode 124. Binary Tree Maximum Path Sum
- LeetCode 124. Binary Tree Maximum Path Sum
- LEETCODE 124. Binary Tree Maximum Path Sum
- 设计模式- 代理模式 (静态代理 和 动态代理)
- 基于sentinel的redis的HA方案
- dll中的内存管理
- Mysql 查询缓存
- mysql将时间戳直接转换成日期时间
- [leetcode] 124. Binary Tree Maximum Path Sum
- hadoop权限说明 2.4.1
- 数据清洗小记(15):DECODE利用sign函数做大小值判断
- 论坛中不同类型的贴的排序问题(涉及数据库的:CASE... END)
- javascript的克隆--深拷贝
- 嵌入式Linux开发教程:Linux内核
- Compressed Texture Formats in Metal
- asp.net mvc 、 ajax 批量上传文件
- RxJava defer操作符