124. Binary Tree Maximum Path Sum
2016-11-16 20:06
260 查看
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 must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
Return 6.
思路:
求最大路径和就等于下面三个值的最大值:
左子树的最大路径和
右子树最大路径和
左子树单路 + 右子树单路 + root.val
如果只是一个节点,那么当然就是这个节点的值了.
如果这个作为root,那么最长路应该就是left+ right+root->val.
当然如果left,或者right<0就不用加了.
最大值是一个全局变量,如果当前路径最大值大于最大值则更新。
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 at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6.
思路:
求最大路径和就等于下面三个值的最大值:
左子树的最大路径和
右子树最大路径和
左子树单路 + 右子树单路 + root.val
如果只是一个节点,那么当然就是这个节点的值了.
如果这个作为root,那么最长路应该就是left+ right+root->val.
当然如果left,或者right<0就不用加了.
最大值是一个全局变量,如果当前路径最大值大于最大值则更新。
class Solution { public: int MaxValue=INT_MIN; int maxPathSum(TreeNode* root) { if(!root) return 0; dfs(root); return MaxValue; } int dfs(TreeNode *root) { if(!root) return 0; int cur=root->val; int leftmax=dfs(root->left); int rightmax=dfs(root->right); if(leftmax>0) cur+=leftmax; if(rightmax>0) cur+=rightmax; if(cur>MaxValue) MaxValue=cur; return max(root->val,max(root->val+leftmax,root->val+rightmax)); } };
相关文章推荐
- 【Leetcode-Hard-124】Binary Tree Maximum Path Sum
- LeetCode(124) Binary Tree Maximum Path Sum
- leetcode 124: Binary Tree Maximum Path Sum
- LeetCode124 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
- 124. Binary Tree Maximum Path Sum
- [Leetcode 124, Hard] 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 二叉树最大路径和
- 124. Binary Tree Maximum Path Sum
- 124. Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum 树形动态规划
- 124_binaryTreeMaximumPathSum
- LeetCode124 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