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
.
Solution:
/**
* 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) {
int maxSum = root ? root->val : 0;
dfs(root, maxSum);
return maxSum;
}
int dfs(TreeNode *root, int &maxSum)
{
if(!root) return 0;
int left = dfs(root->left, maxSum);
int right = dfs(root->right, maxSum);
maxSum = max(maxSum, root->val + max(left, 0) + max(right, 0));
return root->val + max(max(left, right), 0);
}
};