###### Leetcode 124. Binary Tree Maximum Path Sum

1，最长路径和，必定是以某个节点为根，以此节点左子树的根到某个节点的最大路径，以此节点右子树的根到某节点的最大路径，的和。

2.对于一个节点，只存在3种情况，此节点是最长路径和的根，最长路径和的根在此节点的左子树，最长路径和的根在此节点的右子树

3.可以用递归解决，用maxpathsum变量存最大路径和。用onepath存从根为某个节点的最大路径，

onepath = max(root->left:onepath,root->right:onepath,0) + root->val;

maxpathsum = max(onepath,maxpathsum);

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root) {
if(root == NULL)
return 0;
pathmax = (1<<31);
MaxPathSum(root);

return pathmax;
}
int MaxPathSum(TreeNode* root){
if(root == NULL)
return 0;

int onepath,lpath,rpath,maxsum;
//onepath根到某节点的最大单项路径和
//lpath，rpath，子树的onepath
//maxsum以root为根的最大路径和

lpath = MaxPathSum(root->left);
rpath = MaxPathSum(root->right);

if(lpath<0 && rpath<0)
onepath = root->val;
else
onepath = (lpath>rpath?lpath:rpath) + root->val;

maxsum = root->val;//
if(lpath > 0)
maxsum += lpath;
if(rpath > 0)
maxsum += rpath;
cout<< onepath<<endl;
pathmax = pathmax>(maxsum)?pathmax:maxsum;
return onepath;
}
int pathmax;

};

#### LeetCode（124） Binary Tree Maximum Path Sum

2015-12-27 16:20:25

#### LeetCode 124: Binary Tree Maximum Path Sum 树形动态规划

2015-09-02 15:52:14

#### Binary Tree Maximum Path Sum -- LeetCode

2014-04-05 02:19:00

#### [leetcode-124]Binary Tree Maximum Path Sum(c++)

2015-08-12 15:49:49

#### LeetCode Binary Tree Maximum Path Sum 解题报告

2014-02-06 22:43:45

#### [leetcode] 124. Binary Tree Maximum Path Sum

2015-07-03 13:58:25

#### LeetCode 124. Binary Tree Maximum Path Sum（二叉树最大路径和）

2016-05-27 00:27:32

#### 【LeetCode】Binary Tree Maximum Path Sum 解题报告

2015-01-22 16:15:05

#### Path Sum II -- LeetCode

2014-04-14 23:59:49

#### LeetCode 124:Binary Tree Maximum Path Sum

2015-12-30 22:36:02

## 不良信息举报

Leetcode 124. Binary Tree Maximum Path Sum