124. Binary Tree Maximum Path Sum
和543. Diameter of Binary Tree很像
1 | /** |
稍微改改,思想没变,但可以少1次的判断 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution {
public:
int maxPathSum(TreeNode* root) {
int curMax = INT_MIN;
helper(root, curMax);
return curMax;
}
private:
int helper(TreeNode* node, int& curMax)
{
if(!node)
return 0;
auto left = max(helper(node->left, curMax), 0);
auto right = max(helper(node->right, curMax), 0);
auto curSum = left + right + node->val;
curMax = max(curSum, curMax);
return max(left, right) + node->val;
}
};