[leetcode] Binary Tree Maximum Path Sum
2014-08-09 16:08
337 查看
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
Return
思路:从底部往顶部搜索,参考链接:http://blog.csdn.net/andrewseu/article/details/28687763
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int max1=INT_MIN;
int maxPathSum(TreeNode *root){
if(!root) return 0;
maxpath(root);
return max1;
}
int maxpath(TreeNode *root){
if(!root) return 0;
int left=maxpath(root->left);
int right=maxpath(root->right);
int sum=root->val;
if(left>0) sum+=left;
if(right>0) sum+=right;
max1=max(max1,sum);
return (max(left,right)>0)?(max(left,right)+root->val):root->val;
}
};
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return
6.
思路:从底部往顶部搜索,参考链接:http://blog.csdn.net/andrewseu/article/details/28687763
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int max1=INT_MIN;
int maxPathSum(TreeNode *root){
if(!root) return 0;
maxpath(root);
return max1;
}
int maxpath(TreeNode *root){
if(!root) return 0;
int left=maxpath(root->left);
int right=maxpath(root->right);
int sum=root->val;
if(left>0) sum+=left;
if(right>0) sum+=right;
max1=max(max1,sum);
return (max(left,right)>0)?(max(left,right)+root->val):root->val;
}
};
相关文章推荐
- leetcode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum (Java)
- LeetCode | Binary Tree Maximum Path Sum
- [Leetcode][python]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 124: Binary Tree Maximum Path Sum 树形动态规划
- LeetCode: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 Binary Tree Maximum Path Sum
- Leetcode | Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- leetcode之Binary Tree Maximum Path Sum