|
| 1 | +#include <iostream> |
| 2 | +#include <algorithm> // For max function |
| 3 | + |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +// Definition for a binary tree node. |
| 7 | +struct TreeNode { |
| 8 | + int val; |
| 9 | + TreeNode* left; |
| 10 | + TreeNode* right; |
| 11 | + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 12 | +}; |
| 13 | + |
| 14 | +class Solution { |
| 15 | +public: |
| 16 | + int maxPathSum(TreeNode* root) { |
| 17 | + int maxSum = INT_MIN; // Initialize with the minimum possible value |
| 18 | + findMaxPathSum(root, maxSum); |
| 19 | + return maxSum; |
| 20 | + } |
| 21 | + |
| 22 | +private: |
| 23 | + int findMaxPathSum(TreeNode* node, int& maxSum) { |
| 24 | + if (!node) { |
| 25 | + return 0; |
| 26 | + } |
| 27 | + |
| 28 | + // Calculate the maximum path sum for the left and right subtrees |
| 29 | + int leftMax = max(0, findMaxPathSum(node->left, maxSum)); |
| 30 | + int rightMax = max(0, findMaxPathSum(node->right, maxSum)); |
| 31 | + |
| 32 | + // Calculate the maximum path sum that includes the current node |
| 33 | + int currentMax = node->val + leftMax + rightMax; |
| 34 | + |
| 35 | + // Update the overall maximum path sum |
| 36 | + maxSum = max(maxSum, currentMax); |
| 37 | + |
| 38 | + // Return the maximum path sum that can be extended from this node |
| 39 | + return node->val + max(leftMax, rightMax); |
| 40 | + } |
| 41 | +}; |
| 42 | + |
| 43 | +int main() { |
| 44 | + // Create a sample binary tree |
| 45 | + TreeNode* root = new TreeNode(10); |
| 46 | + root->left = new TreeNode(2); |
| 47 | + root->right = new TreeNode(10); |
| 48 | + root->left->left = new TreeNode(20); |
| 49 | + root->left->right = new TreeNode(1); |
| 50 | + root->right->right = new TreeNode(-25); |
| 51 | + root->right->right->left = new TreeNode(3); |
| 52 | + root->right->right->right = new TreeNode(4); |
| 53 | + |
| 54 | + Solution solution; |
| 55 | + int maxSum = solution.maxPathSum(root); |
| 56 | + |
| 57 | + cout << "Maximum Path Sum: " << maxSum << endl; |
| 58 | + |
| 59 | + return 0; |
| 60 | +} |
0 commit comments