-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch_tree.c
80 lines (60 loc) · 1.55 KB
/
search_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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "common.h"
#include "search_tree.h"
#include "tree.h"
void search_tree_init(Search_tree *tree)
{
tree->root = NULL;
}
void search_tree_free(Search_tree *tree)
{
tree_free(tree->root);
}
// Returns the address of the pointer to the node holding 'key'. If 'key' does
// not exist in the tree, returns the address of the (NULL) pointer that could
// be updated to insert it.
static Tree_node **get_node_ptr(Search_tree *tree, int key)
{
Tree_node **cur = &tree->root;
while (*cur && key != (*cur)->key)
cur = (key < (*cur)->key) ? &(*cur)->left : &(*cur)->right;
return cur;
}
bool search_tree_set(Search_tree *tree, int key, int val, int *old_val)
{
Tree_node **node = get_node_ptr(tree, key);
if (*node == NULL) {
*node = create_node(key, val, NULL, NULL);
return false;
}
if (old_val != NULL)
*old_val = (*node)->val;
(*node)->val = val;
return true;
}
bool search_tree_get(Search_tree *tree, int key, int *val)
{
Tree_node *node = *get_node_ptr(tree, key);
if (node == NULL)
return false;
if (val != NULL)
*val = node->val;
return true;
}
bool search_tree_remove(Search_tree *tree, int key, int *val)
{
Tree_node **node = get_node_ptr(tree, key);
if (*node == NULL)
return false;
if (val != NULL)
*val = (*node)->val;
tree_remove(node);
return true;
}
bool search_tree_valid(Search_tree *tree)
{
return valid_bin_search_tree(tree->root);
}
void search_tree_print(Search_tree *tree)
{
tree_print(tree->root);
}