A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node’s values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Input: 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 = 42.
From: LeetCode
Link: 124. Binary Tree Maximum Path Sum
Overview:
The problem is to find the maximum path sum in a binary tree. A “path” here means any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Approach:
To solve this problem, we perform a post-order traversal of the tree. For each node, we calculate two things:
The reason we need both values is that while the first one (endpoint value) helps us build the path sum for the parent node, the second value (including the current node) helps us track the global maximum path sum across the tree.
Code Explanation:
helper function: This is a recursive function that traverses the binary tree in a post-order manner. It calculates the maximum path sum for each node and updates the global maximum path sum.
globalMax: This variable keeps track of the maximum path sum encountered so far across the entire tree.
leftMax and rightMax: For each node, we calculate the maximum path sum for its left child and right child.
maxSingle: This represents the maximum path sum considering the current node as an endpoint. This is calculated as the maximum of:
globalMax update: For each node, we update the globalMax to be the maximum of the current globalMax and maxTop.
Returning from helper function: We return maxSingle because this represents the maximum value that can be used to form a path sum for the current node’s parent.
maxPathSum function: This function initializes the globalMax to the smallest possible integer value and then calls the helper function to traverse the tree and find the maximum path sum. Finally, it returns the globalMax.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int helper(struct TreeNode* root, int* globalMax) {
if (!root) {
return 0;
}
int leftMax = helper(root->left, globalMax);
int rightMax = helper(root->right, globalMax);
int maxSingle = fmax(fmax(leftMax, rightMax) + root->val, root->val);
int maxTop = fmax(maxSingle, leftMax + rightMax + root->val);
*globalMax = fmax(*globalMax, maxTop);
return maxSingle;
}
int maxPathSum(struct TreeNode* root) {
int globalMax = INT_MIN;
helper(root, &globalMax);
return globalMax;
}