124. Binary Tree Maximum Path Sum
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int max_sum = INT_MIN;
int myMaxPathSum(TreeNode* root) {
if(!root) return 0;
int left_max = myMaxPathSum(root->left);
int right_max = myMaxPathSum(root->right);
int max_path = max(root->val, max(left_max, right_max) + root->val);
max_sum = max(max_sum, max_path);
max_sum = max(max_sum, left_max + right_max + root->val);
return max_path;
}
int maxPathSum(TreeNode* root) {
myMaxPathSum(root);
return max_sum;
}
};