-
Notifications
You must be signed in to change notification settings - Fork 0
/
131-heap_insert.c
68 lines (60 loc) · 1.79 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
62
63
64
65
66
67
68
#include "binary_trees.h"
/**
* 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
* 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;
/* subtract all nodes except for bottom-most level */
for (bit = 1 << (level - 1); bit != 1; bit >>= 1)
tree = leaves & bit ? tree->right : tree->left;
/*
* Traverse tree to first empty slot based on the binary
* representation of the number of leaves.
* Example -
* If there are 12 nodes in a complete tree, there are 5 leaves on
* the 4th tier of the tree. 5 is 101 in binary. 1 corresponds to
* right, 0 to left.
* The first empty node is 101 == RLR, *root->right->left->right
*/
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;
}
/* Flip values with parent until parent value exceeds new value */
return (new);
}
/**
* binary_tree_size - measures the size of a binary tree
* @tree: tree to measure the size of
*
* 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);
}