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 {
public:
int ans;
int maxx(TreeNode *root){
if(root == NULL) return 0;
int s1 = maxx(root -> left);
int s2 = maxx(root -> right);
int num = root -> val;
if(s1 > 0) num += s1;
if(s2 > 0) num += s2;
if(ans < num) ans = num;
return max(root -> val,max(s1,s2) + root -> val);
}
int maxPathSum(TreeNode *root) {
ans = root -> val;
maxx(root);
return ans;
}
};