#include <iostream>
#include <climits>
using namespace std;
/*
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node
to any node in the tree along the parent-child connections. The path does not need
to go through the root.
Example:
1
2 3
return 1 + 2 + 3 = 6
*/
/*
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
}
*/
int maxPathSum(TreeNode* root, int& maxValue) {
if(!root) return 0;
int leftLegValue = maxPathSum(root->left, maxValue);
int rightLeftValue = maxPathSum(root->right, maxValue);
int m = root->val;
int longerLeg = max(leftLegValue, rightLegValue);
// maximum result which contains the root.
int result = max(m, m + longerLeg);
int maxPath = m;
maxPath = max(maxPath, maxPath + leftLegValue);
maxPath = max(maxPath, maxPath + rightLegValue);
maxValue = max(maxValue, maxPath);
return result;
}
int maxPathSum(TreeNode* root) {
int maxValue = INT_MIN;
maxPathSum(root, maxValue);
return maxValue;
}
LeetCode 124. Binary Tree Maximum Path Sum
最新推荐文章于 2024-03-25 21:39:45 发布