Binary Tree Maximum Path Sum Algorithm
The Binary Tree Maximum Path Sum Algorithm is a technique used in computer science to find the maximum path sum in a binary tree, where the path may start and end at any node in the tree. A binary tree is a data structure in which each node has at most two children, which are referred to as the left child and the right child. The path sum is calculated by summing up the values of the nodes traversed in a particular path. The algorithm aims to identify the path with the highest sum by traversing the tree in an efficient manner.
The algorithm works through a depth-first search traversal of the binary tree, where it explores as far as possible along each branch before backtracking. At each node, the algorithm calculates the maximum path sum that includes the current node, considering the values of the left and right children. It also maintains a global variable to keep track of the overall maximum path sum found during the traversal. The key idea is to compute the maximum path sum for each node in a bottom-up manner, starting from the leaves and going up to the root. This allows the algorithm to efficiently find the maximum path sum without having to explore all possible paths in the tree, resulting in a time complexity of O(n), where n is the number of nodes in the tree.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode *root) {
if (root == NULL) {
return 0;
}
int maxsum = INT_MIN;
dfs(root, &maxsum);
return maxsum;
}
int dfs(TreeNode* node, int* maxsum) {
if (node == NULL) {
return 0;
}
int left = dfs(node->left, maxsum);
int right = dfs(node->right, maxsum);
int val = node->val;
if (max(left, right) > 0) {
val += max(left, right);
}
int sum = node->val;
if (left > 0) {
sum += left;
}
if (right > 0) {
sum += right;
}
*maxsum = max(*maxsum, sum);
return val;
}
};