定义一个辅助函数,返回从当前根节点,到另一个节点的最大值。因此根据可以写出以下代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root) {
maxSum(root);
return res;
}
int res = INT_MIN;
int maxSum(TreeNode* root){
if(root == NULL){
return 0;
}
int left = max(maxSum(root->left), 0);
int right = max(maxSum(root->right), 0);
res = max(res, root->val + left + right);
return root->val + max(left,right);
}
};