data_structures
rbt_put.c
Go to the documentation of this file.
1 /* ************************************************************************** */
3 /* */
4 /* ::: :::::::: */
5 /* rbt_put.c :+: :+: :+: */
6 /* +:+ +:+ +:+ */
7 /* By: unite <marvin@42.fr> +#+ +:+ +#+ */
8 /* +#+#+#+#+#+ +#+ */
9 /* Created: 2020/07/18 13:46:33 by unite #+# #+# */
10 /* Updated: 2020/09/07 22:09:03 by unite ### ########.fr */
11 /* */
12 /* ************************************************************************** */
13 
14 #include "rbt.h"
15 #include "rbt_utils.h"
16 
17 static t_rbt_node *rbt_put_recur(t_rbt *rbt, t_rbt_node *node,
18  const void *key, const void *val)
19 {
20  int cmp;
21 
22  if (node == NULL)
23  return (rbt_make_node(rbt, key, val, RBT_RED));
24  cmp = rbt->key_type->cmp(key, node->key);
25  if (cmp < 0)
26  node->left = rbt_put_recur(rbt, node->left, key, val);
27  else if (cmp > 0)
28  node->right = rbt_put_recur(rbt, node->right, key, val);
29  else
30  {
31  rbt->val_type->del(node->val);
32  node->val = rbt->val_type->copy(val);
33  }
34  if (rbt_is_red_node(node->right) && !rbt_is_red_node(node->left))
35  node = rbt_rotate_left(rbt, node);
36  if (rbt_is_red_node(node->left) && rbt_is_red_node(node->left->left))
37  node = rbt_rotate_right(rbt, node);
38  if (rbt_is_red_node(node->left) && rbt_is_red_node(node->right))
39  rbt_flip_color(rbt, node);
40  node->count = 1 +
41  rbt_size_subtree(node->left) + rbt_size_subtree(node->right);
42  return (node);
43 }
44 
45 void rbt_put(t_rbt *rbt, const void *key, const void *val)
46 {
47  rbt->root = rbt_put_recur(rbt, rbt->root, key, val);
48 }
s_type::copy
void *(* copy)(const void *)
A function pointer used to copy the data type.
Definition: types.h:50
s_rbt
A left-leaning red-black binary search tree.
Definition: rbt.h:72
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_rbt_node::right
struct s_rbt_node * right
The right child.
Definition: rbt.h:56
s_rbt_node::count
size_t count
The number of this node's children.
Definition: rbt.h:58
s_rbt_node::left
struct s_rbt_node * left
The left child.
Definition: rbt.h:55
s_rbt::val_type
const t_type * val_type
The type of values in the ree.
Definition: rbt.h:76
s_rbt_node::key
void * key
The key.
Definition: rbt.h:53
s_type::del
void(* del)(void *)
A function pointer used to free the memory taken by the data type.
Definition: types.h:51
s_rbt::key_type
const t_type * key_type
The type of keys in the tree.
Definition: rbt.h:75
rbt.h
rbt_utils.h
rbt_put
void rbt_put(t_rbt *rbt, const void *key, const void *val)
Adds a new item to the tree or overwrites an existing one.
Definition: rbt_put.c:45
s_rbt_node
A node in a red-black tree.
Definition: rbt.h:51
s_rbt::root
t_rbt_node * root
The root of the tree.
Definition: rbt.h:74
s_rbt_node::val
void * val
The value.
Definition: rbt.h:54