-
Notifications
You must be signed in to change notification settings - Fork 0
/
1530 Number of good leaf nodes pairs.c
75 lines (63 loc) · 1.65 KB
/
1530 Number of good leaf nodes pairs.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int total_count = 0;
int * count(struct TreeNode * root, int distance, int * arr_index)
{
if(root == NULL)
return;
int left_arr_index = 0;
int right_arr_index = 0;
int * left_arr = count(root->left, distance, &left_arr_index);
int * right_arr = count(root->right, distance, &right_arr_index);
if(root->left==NULL && root->right==NULL)
{
int * ret_arr = (int *)malloc(sizeof(int) * 1);
ret_arr[0] = 1;
*arr_index = 1;
return ret_arr;
}
int * tmp_arr = (int *)malloc(sizeof(int) * (left_arr_index + right_arr_index));
int tmp_arr_index = 0;
int i=0;
for(i=0; i<left_arr_index; i++)
{
tmp_arr[tmp_arr_index++] = left_arr[i];
}
for(i=0; i<right_arr_index; i++)
{
tmp_arr[tmp_arr_index++] = right_arr[i];
}
//Check whether any of the pair satisfies the condition
int j=0;
for(i=0; i<left_arr_index; i++)
{
for(j=left_arr_index; j<left_arr_index + right_arr_index; j++)
{
if(tmp_arr[i] + tmp_arr[j] <= distance)
{
total_count++;
}
}
}
*arr_index = tmp_arr_index;
for(i=0; i<tmp_arr_index; i++)
{
tmp_arr[i] += 1;
}
free(left_arr);
free(right_arr);
return tmp_arr;
}
int countPairs(struct TreeNode* root, int distance)
{
total_count = 0;
int arr_index = 0;
int * ret = count(root, distance, &arr_index);
return total_count;
}