Leetcode 124 Solution
This article provides solution to leetcode question 124 (binary-tree-maximum-path-sum)
Access this page by simply typing in "lcs 124" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/binary-tree-maximum-path-sum
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:
void maxPathSum(TreeNode* root, int& maxRootValue, int& maxValue)
{
if (root == NULL)
{
maxRootValue = 0;
return;
}
int leftMaxRootValue, rightMaxRootValue;
maxPathSum(root->left, leftMaxRootValue, maxValue);
maxPathSum(root->right, rightMaxRootValue, maxValue);
if (maxValue < root->val + leftMaxRootValue + rightMaxRootValue)
maxValue = root->val + leftMaxRootValue + rightMaxRootValue;
maxRootValue = max(root->val + max(leftMaxRootValue, rightMaxRootValue), 0);
}
int maxPathSum(TreeNode* root) {
int maxRootValue;
int maxValue = INT_MIN;
maxPathSum(root, maxRootValue, maxValue);
return maxValue;
}
};