data_structures
bst_put.c
Go to the documentation of this file.
1 /* ************************************************************************** */
3 /* */
4 /* ::: :::::::: */
5 /* bst_put.c :+: :+: :+: */
6 /* +:+ +:+ +:+ */
7 /* By: unite <marvin@42.fr> +#+ +:+ +#+ */
8 /* +#+#+#+#+#+ +#+ */
9 /* Created: 2020/07/17 22:09:18 by unite #+# #+# */
10 /* Updated: 2020/09/07 21:44:44 by unite ### ########.fr */
11 /* */
12 /* ************************************************************************** */
13 
14 #include "bst.h"
15 
16 static t_bst_node *bst_make_node(t_bst *bst, const void *key, const void *val)
17 {
18  t_bst_node *node;
19 
20  node = ds_xcalloc(sizeof(t_bst_node), 1);
21  node->key = bst->key_type->copy(key);
22  node->val = bst->val_type->copy(val);
23  return (node);
24 }
25 
26 static t_bst_node *bst_put_recur(t_bst *bst, t_bst_node *node,
27  const void *key, const void *val)
28 {
29  int cmp;
30 
31  if (node == NULL)
32  return (bst_make_node(bst, key, val));
33  cmp = bst->key_type->cmp(key, node->key);
34  if (cmp < 0)
35  node->left = bst_put_recur(bst, node->left, key, val);
36  else if (cmp > 0)
37  node->right = bst_put_recur(bst, node->right, key, val);
38  else
39  {
40  bst->val_type->del(node->val);
41  node->val = bst->val_type->copy(val);
42  }
43  return (node);
44 }
45 
46 void bst_put(t_bst *bst, const void *key, const void *val)
47 {
48  bst->root = bst_put_recur(bst, bst->root, key, val);
49  bst->size++;
50 }
s_type::copy
void *(* copy)(const void *)
A function pointer used to copy the data type.
Definition: types.h:50
bst_put
void bst_put(t_bst *bst, const void *key, const void *val)
Adds a new item to the tree or overwrites an existing one.
Definition: bst_put.c:46
s_bst_node
A node in a binary search tree.
Definition: bst.h:36
s_bst_node::val
void * val
The value.
Definition: bst.h:39
ds_xcalloc
void * ds_xcalloc(size_t count, size_t size)
Replicates behaviour of calloc from libc, but fails on memory allocation errors.
Definition: ds_xcalloc.c:22
s_type::cmp
int(* cmp)(const void *, const void *)
(optional) A function ponter used to compare members of this data type
Definition: types.h:52
s_bst::val_type
const t_type * val_type
The type of values in the ree.
Definition: bst.h:62
s_bst::key_type
const t_type * key_type
The type of keys in the tree.
Definition: bst.h:61
s_bst::size
size_t size
The number of elements in this tree.
Definition: bst.h:60
s_bst_node::right
struct s_bst_node * right
The right child.
Definition: bst.h:41
s_bst_node::left
struct s_bst_node * left
The left child.
Definition: bst.h:40
bst.h
s_type::del
void(* del)(void *)
A function pointer used to free the memory taken by the data type.
Definition: types.h:51
s_bst_node::key
void * key
The key.
Definition: bst.h:38
s_bst
A binary search tree.
Definition: bst.h:57
s_bst::root
t_bst_node * root
The root of the tree.
Definition: bst.h:59