-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathsol.cpp
80 lines (66 loc) · 1.59 KB
/
sol.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
#include <iostream>
#include <vector>
#define INT_MIN -100000000
using namespace std;
struct node{
// Binary Tree data structure
int data;
node *left, *right;
};
node *createNode(int val){
// Function to create a binary tree node
node *temp = new node;
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
int maxDepth(node *root){
// Returns the maximum depth of a binary tree
if (root == NULL) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
void allKeysOfLevel(node *root, int level, vector<int> &keys){
// Collects all keys of a b. tree at a level in a vector
if (root==NULL) return;
if (level==1){
keys.push_back(root->data);
}
if (level>1){
allKeysOfLevel(root->left, level-1, keys);
allKeysOfLevel(root->right, level-1, keys);
}
return;
}
int maxLevelSum(node *root){
// Returns the level with max level sum
int depth = maxDepth(root);
vector<int> v;
int sum, level_max;
int max_levl_sum = INT_MIN;
for (int d=1; d<=depth; d++){
v = {};
sum = 0;
allKeysOfLevel(root, d, v);
for (int i=0; i<v.size(); i++){
sum = sum+v[i];
}
if (sum>max_levl_sum)
level_max = d;
max_levl_sum = sum;
}
return level_max;
}
void test(){
// Create and run a test case
node *root = createNode(3);
root->left = createNode(-3);
root->right = createNode(7);
root->left->left = createNode(30);
root->left->right = createNode(50);
root->right->left = createNode(-100);
cout << "Level with max sum = " << maxLevelSum(root) << endl;;
}
int main(){
// runs the test
test();
}