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.
#include <iostream>
#include <vector>
#include <climits>
using std::vector;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
private:
int maxPathSum(TreeNode *root, int &Result)
{
if (!root)
{
return 0;
}
int RootResult = root->val;
int LeftResult = maxPathSum(root->left, Result);
int RightResult = maxPathSum(root->right, Result);
LeftResult = LeftResult * (LeftResult > 0);
RightResult = RightResult * (RightResult > 0);
// all the tree
int TmpResult = RootResult + LeftResult + RightResult;
if (Result < TmpResult)
{
Result = TmpResult;
}
// only left subtree or the right subtree
TmpResult = RootResult + (LeftResult > RightResult? LeftResult : RightResult);
if (Result < TmpResult)
{
Result = TmpResult;
}
return TmpResult;
}
public:
int maxPathSum(TreeNode* root)
{
int Result = INT_MIN;
maxPathSum(root, Result);
return Result;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode_Binary Tree Maximum Path Sum
原文地址:http://blog.csdn.net/sheng_ai/article/details/46716081