Skip to content

Commit 79f8633

Browse files
Added max_sum_across_levels
1 parent 3069e91 commit 79f8633

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
{
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
struct Node
5+
{
6+
int data;
7+
struct Node *left;
8+
struct Node *right;
9+
10+
Node(int x){
11+
data = x;
12+
left = NULL;
13+
right = NULL;
14+
}
15+
};
16+
/* Computes the number of nodes in a tree. */
17+
int height(struct Node* node)
18+
{
19+
if (node==NULL)
20+
return 0;
21+
else
22+
return 1 + max(height(node->left), height(node->right));
23+
}
24+
int maxLevelSum(Node * root);
25+
/* Function to get diameter of a binary tree */
26+
void inorder(Node *root)
27+
{
28+
if (root == NULL)
29+
return;
30+
inorder(root->left);
31+
cout << root->data << " ";
32+
inorder(root->right);
33+
}
34+
/* Driver program to test size function*/
35+
int main()
36+
{
37+
int t;
38+
scanf("%d
39+
", &t);
40+
while (t--)
41+
{
42+
map<int, Node*> m;
43+
int n;
44+
scanf("%d",&n);
45+
struct Node *root = NULL;
46+
struct Node *child;
47+
while (n--)
48+
{
49+
Node *parent;
50+
char lr;
51+
int n1, n2;
52+
scanf("%d %d %c", &n1, &n2, &lr);
53+
if (m.find(n1) == m.end())
54+
{
55+
parent = new Node(n1);
56+
m[n1] = parent;
57+
if (root == NULL)
58+
root = parent;
59+
}
60+
else
61+
parent = m[n1];
62+
child = new Node(n2);
63+
if (lr == 'L')
64+
parent->left = child;
65+
else
66+
parent->right = child;
67+
m[n2] = child;
68+
}
69+
cout << maxLevelSum(root) << endl;
70+
}
71+
return 0;
72+
}
73+
74+
}
75+
/*This is a function problem.You only need to complete the function given below*/
76+
/* Tree node structure used in the program
77+
struct Node
78+
{
79+
int data;
80+
Node* left, *right;
81+
}; */
82+
/*You are required to complete below method */
83+
84+
85+
int maxLevelSum(Node * root)
86+
{
87+
//Your code here
88+
if(!root) return 0;
89+
90+
queue<Node* > q;
91+
q.push(root);
92+
93+
int max_sum = root->data, curr_sum = 0;
94+
while(!q.empty()){
95+
curr_sum = 0;
96+
int nodeCount = q.size();
97+
while(nodeCount > 0){
98+
99+
Node *currNode = q.front();
100+
q.pop();
101+
curr_sum += currNode->data;
102+
103+
if (currNode->left != NULL)
104+
q.push(currNode->left);
105+
106+
if (currNode->right != NULL)
107+
q.push(currNode->right);
108+
nodeCount--;
109+
}
110+
max_sum = max(curr_sum, max_sum);
111+
}
112+
return max_sum;
113+
}

0 commit comments

Comments
 (0)