Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return6.
思路:
左子树延伸下去的路径
右子树眼神下去的路径
通过根节点的路径
注意返回这和最大值的关系;
class Solution
{
int help(TreeNode* node, int& maxVal)
{
if (!node)
{
return 0;
}
int v1 = help(node->left, maxVal);
int v2 = help(node->right, maxVal);
int v = max(max(v1 + node->val, v2 + node->val), max(v1 + v2 + node->val, node->val));
maxVal = v>maxVal ? v : maxVal;
return max(max(v1 + node->val, v2 + node->val), node->val);//返回链接父节点时的最大值
}
int maxPathSum(TreeNode* root)
{
int maxVal = INI_MIN;
help(root, maxVal);
return maxVal;
}
};