-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path124 Binary Tree Maximum Path Sum.cpp
More file actions
38 lines (38 loc) · 1.19 KB
/
124 Binary Tree Maximum Path Sum.cpp
File metadata and controls
38 lines (38 loc) · 1.19 KB
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
34
35
36
37
38
static int fastio=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
/**
* 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 res=INT_MIN;
int max_value_path(TreeNode* root){
if(root==nullptr)
return 0;
int left=max_value_path(root->left);
int right=max_value_path(root->right);
int temp=max(max(left,right)+root->val,root->val); // replace 1 with root->val, a bit change considering negative numbers
int answer=max(root->val+left+right,temp); // replace 1 with root->val
if(res<answer)
res=answer;
return temp;// passon the elft,right max only when including the root and passing on the root to above
}
int maxPathSum(TreeNode* root) {
if (root==nullptr)
return 0;
max_value_path(root);
return res;
}
};