-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path131-heap_insert.c
executable file
·61 lines (51 loc) · 1.44 KB
/
131-heap_insert.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
#include "binary_trees.h"
heap_t *heap_insert(heap_t **root, int value);
size_t binary_tree_size(const binary_tree_t *tree);
/**
* heap_insert- Inserts a value in Max Binary Heap.
*
* @root: A double pointer to the root node of the Heap to insert the value.
* @value: The value to store in the node to be inserted.
*
* Return: A pointer to the created node, or NULL on failure.
*/
heap_t *heap_insert(heap_t **root, int value)
{
heap_t *tree, *new, *flip;
int size, leaves, sub, bit, level, tmp;
if (!root)
return (NULL);
if (!(*root))
return (*root = binary_tree_node(NULL, value));
tree = *root;
size = binary_tree_size(tree);
leaves = size;
for (level = 0, sub = 1; leaves >= sub; sub *= 2, level++)
leaves -= sub;
for (bit = 1 << (level - 1); bit != 1; bit >>= 1)
tree = leaves & bit ? tree->right : tree->left;
new = binary_tree_node(tree, value);
leaves & 1 ? (tree->right = new) : (tree->left = new);
flip = new;
for (; flip->parent && (flip->n > flip->parent->n); flip = flip->parent)
{
tmp = flip->n;
flip->n = flip->parent->n;
flip->parent->n = tmp;
new = new->parent;
}
return (new);
}
/**
* binary_tree_size - Measures the size of a binary tree.
*
* @tree: A pointer to the tree to be measured.
*
* Return: Size of the tree, 0 if tree is NULL
*/
size_t binary_tree_size(const binary_tree_t *tree)
{
if (!tree)
return (0);
return (binary_tree_size(tree->left) + binary_tree_size(tree->right) + 1);
}