-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path133-heap_extract.c
More file actions
executable file
·87 lines (81 loc) · 1.68 KB
/
133-heap_extract.c
File metadata and controls
executable file
·87 lines (81 loc) · 1.68 KB
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
81
82
83
84
85
86
87
#include "binary_trees.h"
int heap_extract(heap_t **root);
void recurse_extract(heap_t *tree);
heap_t *max(heap_t *tree);
/**
* heap_extract - Extracts the root node of a Max Binary Heap.
*
* @root: A double pointer to the root node of heap.
*
* Return: The value stored in the root node.
*/
int heap_extract(heap_t **root)
{
int value;
if (!*root)
return (0);
value = (*root)->n;
if (!(*root)->left)
{
value = (*root)->n;
free(*root);
*root = NULL;
return (value);
}
recurse_extract(*root);
return (value);
}
/**
* recurse_extract - Recursively extracts the max from the tree.
*
* @tree: The pointer to the root of the tree.
*/
void recurse_extract(heap_t *tree)
{
heap_t *sub_max, *right_max = NULL;
if (!tree->left)
return;
sub_max = max((tree)->left);
if (tree->right)
right_max = max(tree->right);
if (right_max && right_max->n > sub_max->n)
sub_max = right_max;
tree->n = sub_max->n;
if (!sub_max->left)
{
if (sub_max->parent && sub_max->parent->left == sub_max)
sub_max->parent->left = NULL;
if (sub_max->parent && sub_max->parent->right == sub_max)
sub_max->parent->right = NULL;
free(sub_max);
}
else
recurse_extract(sub_max);
}
/**
* max - Finds the maximum node in a tree.
*
* @tree: The pointer to the root of the tree.
*
* Return: The node with the maximum value.
*/
heap_t *max(heap_t *tree)
{
heap_t *curr_max, *left_max, *right_max;
if (!tree->left)
return (tree);
left_max = max(tree->left);
if (left_max->n > tree->n)
curr_max = left_max;
else
curr_max = tree;
if (tree->right)
{
right_max = max(tree->right);
if (right_max->n > curr_max->n)
curr_max = right_max;
else
curr_max = tree;
}
return (curr_max);
}