0%

124. Binary Tree Maximum Path Sum

124. Binary Tree Maximum Path Sum

543. Diameter of Binary Tree很像
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* 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) {
int curMax = INT_MIN;
helper(root, curMax);
return curMax;
}
private:
int helper(TreeNode* node, int& curMax)
{
if(!node)
return 0;

auto left = helper(node->left, curMax);
auto right = helper(node->right, curMax);
auto curSum = (left < 0 ? 0 : left) + (right < 0 ? 0 :right) + node->val;
curMax = max(curSum, curMax);
return max(max(left, right), 0) + node->val;

return 0;
}
};

稍微改改,思想没变,但可以少1次的判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class 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;
}
};