forked from imnishant/GeeksforGeeks-Java-Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxLevelSumInBinaryTree
More file actions
34 lines (33 loc) · 813 Bytes
/
MaxLevelSumInBinaryTree
File metadata and controls
34 lines (33 loc) · 813 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
class GfG
{
public static int maxLevelSum(Node root)
{
if(root == null)
return 0;
Queue<Node> q = new LinkedList<Node>();
q.add(root);
int sum = 0;
int size = 0;
int maxSum = Integer.MIN_VALUE;
while(!q.isEmpty())
{
if(size == 0)
{
size = q.size();
sum = 0;
}
while(size > 0)
{
Node temp = q.poll();
sum += temp.data;
if(temp.left != null)
q.add(temp.left);
if(temp.right != null)
q.add(temp.right);
size--;
}
maxSum = Math.max(maxSum, sum);
}
return maxSum;
}
}