forked from dharmanshu1921/Daa-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum sum of binary tree.cpp
More file actions
102 lines (72 loc) · 1.54 KB
/
Maximum sum of binary tree.cpp
File metadata and controls
102 lines (72 loc) · 1.54 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node* left, * right;
};
Node* newNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
Node* insertLevelOrder(int arr[],
int i, int n)
{
Node *root = nullptr;
if (i < n)
{
root = newNode(arr[i]);
root->left = insertLevelOrder(arr,
2 * i + 1, n);
root->right = insertLevelOrder(arr,
2 * i + 2, n);
}
return root;
}
void inOrder(Node* root)
{
if (root != NULL)
{
inOrder(root->left);
cout << root->data <<" ";
inOrder(root->right);
}
}
int findMaxUtil(Node* root, int& res)
{
if (root == NULL)
return 0;
int l = findMaxUtil(root->left, res);
int r = findMaxUtil(root->right, res);
int max_single
= max(max(l, r) + root->data, root->data);
int max_top = max(max_single, l + r + root->data);
res = max(res, max_top);
return max_single;
}
int findMaxSum(Node* root)
{
int res = INT_MIN;
findMaxUtil(root, res);
return res;
}
int main()
{
int n, i;
cout << "Enter the length of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (i = 0; i < n; i++)
{
cin >> arr[i];
}
Node* root = insertLevelOrder(arr, 0, n);
inOrder(root);
cout<<endl;
cout << "Max path sum is " << findMaxSum(root);
return 0;
}