Given a non-empty 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.
Example 1:
Input: [1,2,3] 1 / \ 2 3 Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42
#include <iostream>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int maxSub(TreeNode* root, int& sum){
if(!root) return 0;
int l = maxSub(root->left, sum);
int r = maxSub(root->right, sum);
int ans = max(root->val, max(root->val + l, max(root->val + r, root->val + l + r)));
if(ans > sum)
sum = ans;
return root->val + max(l, max(r, 0));
}
int maxPathSum(TreeNode* root) {
int sum = INT_MIN;
maxSub(root, sum);
return sum;
}