-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreeADT.c
88 lines (76 loc) · 1.65 KB
/
treeADT.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "treeADT.h"
#include <stdio.h>
#include <stdlib.h>
#define ERROR_ALLOCATION "Error alocando memoria\n"
typedef struct node * pNode;
struct node{
size_t id;
void * elem;
pNode left;
pNode right;
};
struct bstCDT {
pNode root; // raíz del arbol
};
bstADT newtree(void) {
bstADT tree=calloc(1,sizeof(struct bstCDT));
if (tree==NULL)
{
perror(ERROR_ALLOCATION);
exit(EXIT_FAILURE);
}
return tree;
}
static pNode addToTreeRec(pNode root, size_t id, void * elem){
if (root == NULL){
pNode aux =calloc(1,sizeof(struct node));
if (aux==NULL)
{
perror(ERROR_ALLOCATION);
exit(EXIT_FAILURE);
}
aux->id=id;
aux->elem=elem;
return aux;
}
int c=(root->id - id);
if (c < 0){
root->right = addToTreeRec(root->right,id,elem);
}
else if (c>0){
root->left = addToTreeRec(root->left,id,elem);
}
return root;
}
void addToTree(bstADT bst, size_t id, void * elem){
bst->root = addToTreeRec(bst->root,id,elem);
return;
}
void * existIdRec(size_t id, pNode root){
if(root == NULL){
return NULL;
}
int c;
if((c=root->id-id)>0){
return existIdRec(id,root->left);
}
if(c<0){
return existIdRec(id,root->right);
}
return root->elem;
}
void * existId(size_t id,bstADT tree){
return existIdRec(id,tree->root);
}
static void freeTreeRec(pNode root){
if(root == NULL){
return;
}
freeTreeRec(root->left);
freeTreeRec(root->right);
free(root);
}
void freeTree(bstADT root){
freeTreeRec(root->root);
free(root);
}