-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.c
More file actions
632 lines (544 loc) · 14.3 KB
/
tree.c
File metadata and controls
632 lines (544 loc) · 14.3 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "tree.h"
typedef struct node node_t;
/// Struct for tree
struct tree {
node_t *top;
element_copy_fun cpy_f;
element_comp_fun cmp_f;
key_free_fun key_free_f;
element_free_fun elem_free_f;
int size;
};
/// Node struct
struct node {
tree_key_t key;
elem_t value;
node_t *left;
node_t *right;
};
/// Enum for simplifying result of key compares
enum key_compare { KEYS_MATCH, MOVE_RIGHT, MOVE_LEFT };
/// Struct for keeping track of collection of nodes
typedef struct {
int index;
enum { KEYS, VALUES } type;
union {
tree_key_t *keys;
elem_t *values;
};
} node_clt;
/// Creates a new tree
///
/// \param copy (may be NULL) a function applied to all elements when stored in the tree
/// \param key_free (may be NULL) used to free keys in tree_delete
/// \param elem_free (may be NULL) used to free elements in tree_delete
/// \param compare (may be NULL) used to compare keys
/// \returns: empty tree
tree_t *tree_new(element_copy_fun element_copy, key_free_fun key_free, element_free_fun elem_free, element_comp_fun compare)
{
tree_t *new = calloc(1, sizeof(tree_t));
if (new)
{
new->cpy_f = element_copy;
new->cmp_f = compare;
new->key_free_f = key_free;
new->elem_free_f = elem_free;
}
return new;
}
/// Determine if a node is a leaf, e.g. it has no children
///
/// \param node node to check
/// \returns: true if node has no children, false otherwise
bool is_leaf(node_t *node)
{
return node->left == NULL && node->right == NULL;
}
/// Count the amount of children a node has (NOT DEPTH)
///
/// \param node node to count
/// \returns: 0, 1 or 2 depending on count
int count_children(node_t *node)
{
if (node == NULL) return 0;
int count = 0;
if (node->left != NULL) ++count;
if (node->right != NULL) ++count;
return count;
}
/// Frees node and subtrees
///
/// \param tree the tree
/// \param node Node to start remove at
/// \param delete_keys if true, run tree's key_free function on all keys
/// \param delete_elements if true, run tree's elem_free function on all elements
void free_branches(tree_t *tree, node_t *node, bool delete_keys, bool delete_elements)
{
// Frees the left branch of the tree
if (node->left != NULL)
{
free_branches(tree, node->left, delete_keys, delete_elements);
}
// Frees the right branch of the tree
if (node->right != NULL)
{
free_branches(tree, node->right, delete_keys, delete_elements);
}
// Check which key free function to use
if (delete_keys && tree->key_free_f)
{
tree->key_free_f(node->key);
}
// Check which element free function to use
if (delete_elements && tree->elem_free_f)
{
tree->elem_free_f(node->value);
}
free(node);
}
/// Remove a tree along with all elem_t elements.
///
/// \param tree the tree
/// \param delete_keys if true, run tree's key_free function on all keys
/// \param delete_elements if true, run tree's elem_free function on all elements
void tree_delete(tree_t *tree, bool delete_keys, bool delete_elements)
{
if (tree->top != NULL)
{
free_branches(tree, tree->top, delete_keys, delete_elements);
}
free(tree);
}
/// Gets the size of the tree
///
/// \param tree the tree
/// \returns: the number of nodes in the tree
int tree_size(tree_t *tree)
{
return tree->size;
}
/// Return the biggest of two numbers
///
/// \param a First number
/// \param b Second number
/// \returns: Biggest number
int max(int a, int b)
{
return a > b ? a : b;
}
/// Count max node depth
///
/// \param node current node
/// \returns: greatest depth of tree
int count_depth(node_t *node)
{
if (node == NULL)
{
return 0;
}
else if (node->left == NULL && node->right == NULL)
{
return 1;
}
else
{
int left = node->left == NULL ? 1 : 1 + count_depth(node->left);
int right = node->right == NULL ? 1 : 1 + count_depth(node->right);
return max(left, right);
}
}
/// Get the depth of the tree
///
/// \param tree tree to check
/// \returns: the depth of the deepest subtree
int tree_depth(tree_t *tree)
{
return tree->top == NULL ? 0 : count_depth(tree->top);
}
/// Returns which direction to move in tree
/// based on parent and child key
///
/// \param tree associated tree with compare function
/// \param node key of node
/// \param key key to compare with
/// \returns: direction to move in, in the form of an enumerate
enum key_compare compare_keys(tree_t *tree, tree_key_t node_key, tree_key_t cmp_key)
{
int a = (*tree->cmp_f)(node_key, cmp_key);
if (a == 0) return KEYS_MATCH;
else if (a < 0) return MOVE_RIGHT;
else return MOVE_LEFT;
}
/// Finds appropriate position for key in tree, or node
/// if key is in tree.
///
/// \param tree tree to search in
/// \param key key to search tree for
/// \returns: double pointer to correct position
node_t **search_tree(tree_t *tree, tree_key_t key)
{
node_t **node = &(tree->top);
while (*node != NULL)
{
switch(compare_keys(tree, (*node)->key, key))
{
case KEYS_MATCH:
return node;
break;
case MOVE_LEFT:
node = &(*node)->left;
break;
case MOVE_RIGHT:
node = &(*node)->right;
break;
default:
// Something's broken
assert(false);
break;
}
}
// Reached end of branch, key not in tree
return node;
}
/// Traverses all nodes in tree
///
/// \param node current node
/// \param order the order in which the elements will be visited
/// \param fun the function to apply to all elements
/// \param data an extra argument passed to each call to fun (may be NULL)
bool traverse_tree(node_t *node, enum tree_order order, key_elem_apply_fun fun, void *data)
{
if (node != NULL)
{
// PRE ORDER: handle node before both branches
if (order == preorder) fun(node->key, node->value, data);
// traverse left branch
traverse_tree(node->left, order, fun, data);
// IN ORDER: handle node between left and right branches
if (order == inorder) fun(node->key, node->value, data);
// traverse right branch
traverse_tree(node->right, order, fun, data);
// POST ORDER: handle node after both branches
if (order == postorder) fun(node->key, node->value, data);
}
return true;
}
/// Applies a function to all elements in the tree in a specified order.
/// Example (using shelf as key):
///
/// tree_t *t = tree_new();
/// tree_insert(t, "A25", some_item);
/// int number = 0;
/// tree_apply(t, inorder, print_item, &number);
///
/// where print_item is a function that prints the number and increments it,
/// and prints the item passed to it.
///
/// \param tree the tree
/// \param order the order in which the elements will be visited
/// \param fun the function to apply to all elements
/// \param data an extra argument passed to each call to fun (may be NULL)
bool tree_apply(tree_t *tree, enum tree_order order, key_elem_apply_fun fun, void *data)
{
return traverse_tree(tree->top, order, fun, data);
}
/// Determine if a tree is balanced
///
/// \param tree tree to check
/// \returns: true if tree is balanced, otherwise false
bool check_balanced(tree_t *tree)
{
// Empty tree is balanced
if (tree->top == NULL) return true;
// Checks to see the balance of each node
int left_depth = count_depth(tree->top->left);
int right_depth = count_depth(tree->top->right);
int balance_factor = abs(left_depth - right_depth);
return balance_factor < 2;
}
/// Rotates nodes according to AVL right rotation
///
/// \param A top node
/// \returns: new top node
node_t *avl_rotate_left(node_t *A)
{
node_t *B = A->right;
node_t *B_left = B->left;
B->left = A;
A->right = B_left;
return B;
}
/// Rotates nodes according to AVL right rotation
///
/// \param C top node
/// \returns: new top node
node_t *avl_rotate_right(node_t *C)
{
node_t *B = C->left;
node_t *B_right = B->right;
B->right = C;
C->left = B_right;
return B;
}
/// Rotates nodes according to AVL left-right rotation
///
/// \param C top node
/// \returns: new top node
node_t *avl_rotate_left_right(node_t *C)
{
node_t *A = C->left;
node_t *B = A->right;
node_t *B_left = B->left;
B->left = A;
C->left = B;
A->right = B_left;
return avl_rotate_right(C);
}
/// Rotates nodes according to AVL right-left rotation
///
/// \param C top node
/// \returns: new top node
node_t *avl_rotate_right_left(node_t *A)
{
node_t *C = A->right;
node_t *B = C->left;
node_t *B_right = B->right;
B->right = C;
A->right = B;
C->left = B_right;
return avl_rotate_left(A);
}
/// Balances subtree
///
/// \param tree tree that is being balanced
/// \param node top node of current subtree
/// \returns: top node in balanced subtree
node_t *balance_subtree(tree_t *tree, node_t *node)
{
// Balance subtrees
if (node->left) node->left = balance_subtree(tree, node->left);
if (node->right) node->right = balance_subtree(tree, node->right);
// No need to continue balancing if tree is balanced
//if (is_balanced(tree)) return node;
int left_depth = count_depth(node->left);
int right_depth = count_depth(node->right);
int balance_factor = left_depth - right_depth;
// Child node to return
node_t *child = node;
if (balance_factor < -1)
{
// Too many nodes in right subtree
if (count_depth(node->right->left) > count_depth(node->right->right))
{
child = avl_rotate_right_left(node);
}
else
{
child = avl_rotate_left(node);
}
}
else if (balance_factor > 1)
{
// Too many nodes in left subtree
if (count_depth(node->left->right) > count_depth(node->left->left))
{
child = avl_rotate_left_right(node);
}
else
{
child = avl_rotate_right(node);
}
}
return child;
}
/// Balances a tree.
///
/// \param tree tree to be balanced
/// \returns: if balancing was succesful
bool balance_tree(tree_t *tree)
{
node_t *top = tree->top;
if (check_balanced(tree))
{
// No need to rebalance
return true;
}
else
{
tree->top = balance_subtree(tree, top);
return true;
}
return false;
}
/// Insert element into the tree. Returns false if the key is already used.
/// Balances tree after insert.
///
/// \param tree pointer to the tree
/// \param key the key of element to be appended
/// \param elem the element
/// \returns: true if successful, else false
bool tree_insert(tree_t *tree, tree_key_t key, elem_t value)
{
if (tree == NULL) return false;
node_t **leaf = search_tree(tree, key);
if (*leaf == NULL)
{
node_t *new = calloc(1, sizeof(node_t));
new->key = key;
new->value = value;
*leaf = new;
++tree->size;
balance_tree(tree);
assert(check_balanced(tree));
return true;
}
else
{
return false;
}
}
/// Removes node
///
/// \param node the node to be removed
void remove_node(node_t **node)
{
// Three possibilities arise when deleting a node
// 1. The node is a leaf, simply remove it
if (is_leaf(*node))
{
free(*node);
*node = NULL;
}
// 2. Node has one child, replace it with that child
else if (count_children(*node) == 1)
{
node_t *replacement;
if ((*node)->left != NULL)
{
replacement = (*node)->left;
}
else
{
replacement = (*node)->right;
}
free(*node);
*node = replacement;
}
// 3. Node has two children, replace node with inorder successor in tree, remove successor
else
{
// Find successor (the smallest key in right subtree)
node_t **successor = &(*node)->right;
while ((*successor)->left != NULL)
{
successor = &(*successor)->left;
}
(*node)->key = (*successor)->key;
(*node)->value = (*successor)->value;
remove_node(successor);
}
}
/// Removes the element for a given key in tree.
///
/// \param tree pointer to the tree
/// \param key the key of elem to be removed
/// \param result a pointer to where result can be stored (only defined when result is true)
/// \returns: true if key is a key in the tree
bool tree_remove(tree_t *tree, tree_key_t key, elem_t *result)
{
node_t **node = search_tree(tree, key);
if (*node == NULL) return false;
result = &(*node)->value;
remove_node(node);
--tree->size;
balance_tree(tree);
return true;
}
/// Checks whether a key is used in a tree
///
/// \param tree pointer to the tree
/// \param key the key of elem to be removed
/// \returns: true if key is a key in tree
bool tree_has_key(tree_t *tree, tree_key_t key)
{
return *(search_tree(tree, key)) != NULL;
}
/// Returns the element for a given key in tree.
/// (The implementation may assume that the key exists.)
///
/// \param tree pointer to the tree
/// \param key the key of elem to be removed
/// \returns: true if key is a key in tree
bool tree_get(tree_t *tree, tree_key_t key, elem_t *result)
{
node_t **node = search_tree(tree, key);
if (*node == NULL)
{
return false;
}
else
{
*result = (*node)->value;
return true;
}
}
/// Adds key or elem to node_clt, key_elem_apply_fun for tree_elements
/// and tree_keys
///
/// \param key key of node
/// \param elem element of node
/// \param data node_clt to add to
bool collect_nodes(tree_key_t key, elem_t value, void *data)
{
node_clt *clt = data;
if (clt->type == KEYS)
{
clt->keys[clt->index] = key;
}
else
{
clt->values[clt->index] = value;
}
clt->index++;
return true;
}
/// Returns an array holding all the elements in the tree
/// in ascending order of their keys (which are not part
/// of the value).
///
/// \param tree pointer to the tree
/// \returns: array of tree_size() elements
elem_t *tree_elements(tree_t *tree)
{
assert(tree);
int size = tree_size(tree);
elem_t *values = calloc(size, sizeof(elem_t));
node_clt clt = { .index = 0, .type = VALUES, .values = values };
if (size > 0)
{
tree_apply(tree, inorder, collect_nodes, &clt);
}
return values;
}
/// Returns an array holding all the keys in the tree
/// in ascending order.
///
/// \param tree pointer to the tree
/// \returns: array of tree_size() keys
tree_key_t *tree_keys(tree_t *tree)
{
assert(tree);
int size = tree_size(tree);
tree_key_t *keys = calloc(size, sizeof(tree_key_t));
node_clt clt = { .index = 0, .type = KEYS, .keys = keys };
if (size > 0)
{
tree_apply(tree, inorder, collect_nodes, &clt);
}
return keys;
}