forked from imsushant12/GFG-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum_level_sum_in_Binary_Tree.cpp
140 lines (112 loc) · 2.7 KB
/
Maximum_level_sum_in_Binary_Tree.cpp
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
Problem Statement:
-----------------
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it.
Examples:
--------
Input : 4
/ \
2 -5
/ \ /\
-1 3 -2 6
Output: 6
Explanation :
Sum of all nodes of 1'th level is 4
Sum of all nodes of 2'th level is -3
Sum of all nodes of 3'th level is 6
Hence maximum sum is 6
maximum level is 3
Input : 1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Output :
maximum sum is 17
maximum level is 3
*/
// Link --> https://www.geeksforgeeks.org/find-level-maximum-sum-binary-tree/
// Code:
#include <bits/stdc++.h>
using namespace std;
struct treenode
{
int info;
struct treenode *left,*right;
};
treenode* create()
{
int data;
struct treenode *tree = new treenode;
cout<<"\nEnter data to be inserted or type -1 for no insertion : ";
cin>>data;
if(data == -1)
return 0;
tree->info = data;
cout<<"\nEnter left child of "<<data;
tree->left = create();
cout<<"\nEnter right child of "<<data;
tree->right = create();
return tree;
}
void maxLevelSum(treenode* root)
{
queue <treenode *> q1, q2;
q1.push(root);
int final_level = 0 , level = 0;
int sum = 0 , maxsum = 10;
while(!q1.empty() || !q2.empty())
{
if(!q1.empty())
{
level++;
sum = 0;
while(!q1.empty())
{
treenode* temp = q1.front();
q1.pop();
if(temp->left)
q2.push(temp->left);
if(temp->right)
q2.push(temp->right);
sum = sum + temp->info;
}
if(maxsum < sum)
{
maxsum = sum;
final_level = level;
}
}
if(!q2.empty())
{
level++;
sum = 0;
while(!q2.empty())
{
treenode* temp = q2.front();
q2.pop();
if(temp->left)
q1.push(temp->left);
if(temp->right)
q1.push(temp->right);
sum = sum + temp->info;
}
if(maxsum < sum)
{
maxsum = sum;
final_level = level;
}
}
}
cout<<"Maximum sum = "<<maxsum<<endl;
cout<<"Maximum level is : "<<final_level<<endl;
}
int main()
{
struct treenode *root = NULL;
root = create();
maxLevelSum(root);
return 0;
}