-
Notifications
You must be signed in to change notification settings - Fork 0
/
134-heap_to_sorted_array.c
53 lines (41 loc) · 1019 Bytes
/
134-heap_to_sorted_array.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
#include "binary_trees.h"
/**
* tree_size - measures the sum of heights of a binary tree
* @tree: pointer to the root node of the tree to measure the height
*
* Return: Height or 0 if tree is NULL
*/
size_t tree_size(const binary_tree_t *tree)
{
size_t height_l = 0;
size_t height_r = 0;
if (!tree)
return (0);
if (tree->left)
height_l = 1 + tree_size(tree->left);
if (tree->right)
height_r = 1 + tree_size(tree->right);
return (height_l + height_r);
}
/**
* heap_to_sorted_array - converts a Binary Max Heap
* to a sorted array of integers
*
* @heap: pointer to the root node of the heap to convert
* @size: address to store the size of the array
*
* Return: pointer to array sorted in descending order
**/
int *heap_to_sorted_array(heap_t *heap, size_t *size)
{
int i, *a = NULL;
if (!heap || !size)
return (NULL);
*size = tree_size(heap) + 1;
a = malloc(sizeof(int) * (*size));
if (!a)
return (NULL);
for (i = 0; heap; i++)
a[i] = heap_extract(&heap);
return (a);
}