-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxpathsum.cpp
More file actions
59 lines (47 loc) · 1.23 KB
/
maxpathsum.cpp
File metadata and controls
59 lines (47 loc) · 1.23 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <bits/stdc++.h>
using namespace std;
class BinaryTree
{
public:
int value;
BinaryTree*left;
BinaryTree*right;
BinaryTree(int value){
this->value = value;
left = nullptr;
right = nullptr;
}
};
int maxPathSumUtil(BinaryTree*root,int &res)
{
if(root == nullptr)
{
return 0;
}
int left = maxPathSumUtil(root->left,res);
int right = maxPathSumUtil(root->right,res);
int temp = max(max(left,right)+root->value,root->value);
int ans = max(temp,left+right+root->value);
res = max(res,ans);
return temp;
}
int maxPathSum(BinaryTree*tree)
{
int res = INT_MIN;
maxPathSumUtil(tree,res);
return res;
}
int main() {
BinaryTree*root = new BinaryTree(1);
root->left = new BinaryTree(2);
root->right = new BinaryTree(3);
root->left->left = new BinaryTree(4);
root->left->right = new BinaryTree(5);
root->right->left = new BinaryTree(6);
root->right->right = new BinaryTree(7);
// root->left->right->right = new BinaryTree(8);
// root->right->right = new BinaryTree(7);
// root->left->left->left = new BinaryTree(8);
// root->left->left->right = new BinaryTree(9);
cout<<maxPathSum(root);
}