-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtree.c
61 lines (52 loc) · 1.26 KB
/
tree.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
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include "tree.h"
void tree_init(struct tree *t){
t->root = NULL;
}
void* tree_lookup(struct tree *t, uint32_t key){
struct treenode *cur = t->root;
while(cur != NULL){
if( key == cur->key ){
return cur->value;
}else if(key < cur->key ){
cur = cur->left;
}else {
cur = cur->right;
}
}
return NULL;
}
void tree_put(struct tree *t, uint32_t key, void *value){
struct treenode *new = malloc(sizeof(struct treenode));
new->key = key;
new->value = value;
new->left = NULL;
new->right = NULL;
struct treenode *cur = t->root;
if(t->root == NULL){
t->root = new;
return;
}
while(true){
if( key == cur->key ){
cur->value = value;
return;
}else if( key < cur->key ){
if(cur->left == NULL){
cur->left = new;
return;
}else {
cur = cur->left;
}
}else {
if(cur->right == NULL){
cur->right = new;
return;
}else {
cur = cur->right;
}
}
}
}