struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int maxPathSumUtil(TreeNode* root, int& maxSum) {
if (!root) return 0;
int left = std::max(0, maxPathSumUtil(root->left, maxSum));
int right = std::max(0, maxPathSumUtil(root->right, maxSum));
maxSum = std::max(maxSum, left + right + root->val);
return root->val + std::max(left, right);
}
int maxPathSum(TreeNode* root) {
int maxSum = INT_MIN;
maxPathSumUtil(root, maxSum);
return maxSum;
}
int main() {
TreeNode* root = new TreeNode(-10);
root->left = new TreeNode(9);
root->right = new TreeNode(20);
root->right->left = new TreeNode(15);
root->right->right = new TreeNode(7);
std::cout << maxPathSum(root);
return 0;
}The maximum path sum is 42, which comes from the path 15 -> 20 -> 7. The root node (-10) and left child (9) do not contribute to a higher sum.
We use std::max(0, left) and std::max(0, right) to ignore any negative sums from subtrees because including a negative sum would decrease the overall path sum. This way, we only add positive contributions or zero.
int maxPathSumUtil(TreeNode* root, int& maxSum) { if (root == nullptr) return 0; int left = maxPathSumUtil(root->left, maxSum); int right = maxPathSumUtil(root->right, maxSum); maxSum = std::max(maxSum, left + right + root->val); return root->val + std::max(left, right); } int maxPathSum(TreeNode* root) { int maxSum = 0; maxPathSumUtil(root, maxSum); return maxSum; }
The initial maxSum is set to 0, so if all node values are negative, maxSum will never update to a negative value, resulting in an incorrect maximum path sum.
The maximum path sum is 9, coming from the path 2 -> 3 -> 4. Other paths like 3 -> 4 sum to 7, which is lower.
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int maxPathSumUtil(TreeNode* root, int& maxSum) {
if (!root) return 0;
int left = std::max(0, maxPathSumUtil(root->left, maxSum));
int right = std::max(0, maxPathSumUtil(root->right, maxSum));
maxSum = std::max(maxSum, left + right + root->val);
return root->val + std::max(left, right);
}
int maxPathSum(TreeNode* root) {
int maxSum = INT_MIN;
maxPathSumUtil(root, maxSum);
return maxSum;
}
int main() {
TreeNode* root = new TreeNode(-5);
std::cout << maxPathSum(root);
return 0;
}Since the tree has only one node with value -5, the maximum path sum is -5.
