17. Binary Tree Maximum Path Sum
Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42Solution: (Using Postorder)
Approach:
class Solution
{
public:
int findMaxSum(TreeNode *node, int &res)
{
if (node == NULL)
{
return 0;
}
int leftSum = findMaxSum(node->left, res);
int rightSum = findMaxSum(node->right, res);
int max_straight = max(max(leftSum, rightSum) + node->val, node->val); //case-1
int max_root = max(leftSum + rightSum + node->val, max_straight); //case-2
res = max(res, max_root);
return max_straight;
}
int maxPathSum(TreeNode *root)
{
int max_val = INT_MIN;
int res = findMaxSum(root, max_val);
return max_val;
}
};Previous16. Construct Binary Tree from Inorder and Postorder TraversalNext18. Sum Root to Leaf Numbers
Last updated

