-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm1302.c
57 lines (50 loc) · 1.18 KB
/
m1302.c
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
// Not that efficient :l
// probs cause of all the mallocing
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int* helper(struct TreeNode* current) {
if (!current->left && !current->right) {
int* output = (int*) malloc(sizeof(int) * 2);
output[0] = current->val;
output[1] = 1;
return output;
}
if (!current->left) {
int* right = helper(current->right);
right[1] += 1;
return right;
}
if (!current->right) {
int* left = helper(current->left);
left[1] += 1;
return left;
}
int* left = helper(current->left);
int* right = helper(current->right);
if (left[1] == right[1]) {
left[0] += right[0];
left[1] += 1;
free(right);
return left;
} else if (left[1] > right[1]) {
free(right);
left[1] += 1;
return left;
} else {
free(left);
right[1] += 1;
return right;
}
}
int deepestLeavesSum(struct TreeNode* root) {
int* output = helper(root);
int out = output[0];
free(output);
return out;
}