
124 Binary Tree Maximum Path Sum
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,
1
/ \
2 3
Return 6.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int max;
private:
int DFS(TreeNode *root)
{
int left , right , value;
if(root == NULL)
return 0;
left = DFS(root->left);
right = DFS(root->right);
value = root->val;
if(left>0)
value += left;
if(right>0)
value += right;
if(value > max)
max = value;
if(left>right && left>0)
return root->val + left;
if(left<right && right>0)
return root->val + right;
return root->val;
}
public:
int maxPathSum(TreeNode *root) {
max = -1000000;
DFS(root);
return max;
}
};leetcode_124_Binary Tree Maximum Path Sum
原文地址:http://blog.csdn.net/keyyuanxin/article/details/44197147