-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ3.cpp
More file actions
50 lines (37 loc) · 1014 Bytes
/
Q3.cpp
File metadata and controls
50 lines (37 loc) · 1014 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int dfs(TreeNode* root, int& maxi) {
if (root == nullptr)
return 0;
int left = max(dfs(root->left, maxi), 0);
int right = max(dfs(root->right, maxi), 0);
int total = root->val + left + right;
maxi = max(total, maxi);
return root->val + max(left, right);
}
int maxPathSum(TreeNode* root) {
int maxi = INT_MIN;
dfs(root, maxi);
return maxi;
}
TreeNode* newNode(int val) {
TreeNode* node = new TreeNode(val);
node->left = nullptr;
node->right = nullptr;
return node;
}
int main() {
TreeNode* root = newNode(-10);
root->left = newNode(9);
root->right = newNode(20);
root->right->left = newNode(15);
root->right->right = newNode(7);
cout << "The maximum path sum is: " << maxPathSum(root) << endl;
return 0;
}