-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path124.cpp
More file actions
28 lines (27 loc) · 734 Bytes
/
124.cpp
File metadata and controls
28 lines (27 loc) · 734 Bytes
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
// recursion.cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
int maxSum = INT_MIN;
int maxPath(TreeNode* root) {
if (root == nullptr)
return 0;
int left = maxPath(root->left), right = maxPath(root->right);
maxSum = max(maxSum, root->val + (left > 0 ? left : 0) +
(right > 0 ? right : 0));
int sub = max(left, right);
return max(sub + root->val, root->val);
}
public:
int maxPathSum(TreeNode* root) {
maxPath(root);
return maxSum;
}
};