Line | Count | Source |
1 | | /* |
2 | | * Copyright 2020 Google LLC |
3 | | * |
4 | | * Use of this source code is governed by a BSD-style |
5 | | * license that can be found in the LICENSE file or at |
6 | | * https://developers.google.com/open-source/licenses/bsd |
7 | | */ |
8 | | |
9 | | #include "system.h" |
10 | | #include "tree.h" |
11 | | |
12 | | #include "basics.h" |
13 | | |
14 | | struct tree_node *tree_search(struct tree_node *tree, |
15 | | void *key, |
16 | | int (*compare)(const void *, const void *)) |
17 | 0 | { |
18 | 0 | int res; |
19 | 0 | if (!tree) |
20 | 0 | return NULL; |
21 | 0 | res = compare(key, tree->key); |
22 | 0 | if (res < 0) |
23 | 0 | return tree_search(tree->left, key, compare); |
24 | 0 | else if (res > 0) |
25 | 0 | return tree_search(tree->right, key, compare); |
26 | 0 | return tree; |
27 | 0 | } |
28 | | |
29 | | struct tree_node *tree_insert(struct tree_node **rootp, |
30 | | void *key, |
31 | | int (*compare)(const void *, const void *)) |
32 | 0 | { |
33 | 0 | int res; |
34 | |
|
35 | 0 | if (!*rootp) { |
36 | 0 | struct tree_node *n; |
37 | |
|
38 | 0 | REFTABLE_CALLOC_ARRAY(n, 1); |
39 | 0 | if (!n) |
40 | 0 | return NULL; |
41 | | |
42 | 0 | n->key = key; |
43 | 0 | *rootp = n; |
44 | 0 | return *rootp; |
45 | 0 | } |
46 | | |
47 | 0 | res = compare(key, (*rootp)->key); |
48 | 0 | if (res < 0) |
49 | 0 | return tree_insert(&(*rootp)->left, key, compare); |
50 | 0 | else if (res > 0) |
51 | 0 | return tree_insert(&(*rootp)->right, key, compare); |
52 | 0 | return *rootp; |
53 | 0 | } |
54 | | |
55 | | void infix_walk(struct tree_node *t, void (*action)(void *arg, void *key), |
56 | | void *arg) |
57 | 0 | { |
58 | 0 | if (t->left) |
59 | 0 | infix_walk(t->left, action, arg); |
60 | 0 | action(arg, t->key); |
61 | 0 | if (t->right) |
62 | 0 | infix_walk(t->right, action, arg); |
63 | 0 | } |
64 | | |
65 | | void tree_free(struct tree_node *t) |
66 | 0 | { |
67 | 0 | if (!t) |
68 | 0 | return; |
69 | 0 | if (t->left) |
70 | 0 | tree_free(t->left); |
71 | 0 | if (t->right) |
72 | 0 | tree_free(t->right); |
73 | 0 | reftable_free(t); |
74 | 0 | } |