Difficulty: Hard
Given a 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 does not need to go through the root.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6
.
/**
* 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 {
int maxRes=INT_MIN;
int helper(TreeNode *root){
if(!root)
return 0;
int left =helper(root->left);
int right=helper(root->right);
int tempMax=max(0,max(left,right));
maxRes=max(root->val+tempMax,max(left+right+root->val,maxRes));
return root->val+tempMax;
}
public:
int maxPathSum(TreeNode* root) {
if(!root)
return 0;
helper(root);
return maxRes;
}
};