LeetCode Binary Tree Maximum Path Sum nice bottom up recursion
/**
* 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 fun(TreeNode* root,int *max_sum)
{
if(root==NULL)
return 0;
int ls=fun(root->left,max_sum);
int rs=fun(root->right,max_sum);
int mx=max(max(root->val+ls,root->val+rs),root->val+ls+rs);
mx=max(mx,root->val);
if(mx>(*max_sum))
(*max_sum)=mx;
return max(max(root->val+ls,root->val+rs),root->val);
}
int maxPathSum(TreeNode* root) {
int max_sum=INT_MIN;
fun(root,&max_sum);
return max_sum;
}
};
No comments:
Post a Comment