Given a non-empty 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 must contain at least one node and does not need to go through the root.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
通过子函数获得每个节点能贡献的最大值,
在这个过程中不断更新结果。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res = INT_MIN;
int maxGain(TreeNode* root)
{
if(root == nullptr){
return 0;
}
int leftGain = max(0, maxGain(root->left));
int rightGain = max(0, maxGain(root->right));
res = max(res, root->val + leftGain +rightGain);
return root->val + max(leftGain, rightGain);
}
int maxPathSum(TreeNode* root) {
maxGain(root);
return res;
}
};
其实发现这道题和寻找二叉树最大直径有点像