1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
34 #include "gtestutils.h"
38 * SECTION:trees-binary
39 * @title: Balanced Binary Trees
40 * @short_description: a sorted collection of key/value pairs optimized
41 * for searching and traversing in order
43 * The #GTree structure and its associated functions provide a sorted
44 * collection of key/value pairs optimized for searching and traversing
47 * To create a new #GTree use g_tree_new().
49 * To insert a key/value pair into a #GTree use g_tree_insert().
51 * To lookup the value corresponding to a given key, use
52 * g_tree_lookup() and g_tree_lookup_extended().
54 * To find out the number of nodes in a #GTree, use g_tree_nnodes(). To
55 * get the height of a #GTree, use g_tree_height().
57 * To traverse a #GTree, calling a function for each node visited in
58 * the traversal, use g_tree_foreach().
60 * To remove a key/value pair use g_tree_remove().
62 * To destroy a #GTree, use g_tree_destroy().
67 #define MAX_GTREE_HEIGHT 40
69 typedef struct _GTreeNode GTreeNode;
74 * The GTree struct is an opaque data structure representing a
75 * [balanced binary tree][glib-Balanced-Binary-Trees]. It should be
76 * accessed only by using the following functions.
81 GCompareDataFunc key_compare;
82 GDestroyNotify key_destroy_func;
83 GDestroyNotify value_destroy_func;
84 gpointer key_compare_data;
91 gpointer key; /* key for this node */
92 gpointer value; /* value stored at this node */
93 GTreeNode *left; /* left subtree */
94 GTreeNode *right; /* right subtree */
95 gint8 balance; /* height (right) - height (left) */
101 static GTreeNode* g_tree_node_new (gpointer key,
103 static void g_tree_insert_internal (GTree *tree,
107 static gboolean g_tree_remove_internal (GTree *tree,
110 static GTreeNode* g_tree_node_balance (GTreeNode *node);
111 static GTreeNode *g_tree_find_node (GTree *tree,
113 static gint g_tree_node_pre_order (GTreeNode *node,
114 GTraverseFunc traverse_func,
116 static gint g_tree_node_in_order (GTreeNode *node,
117 GTraverseFunc traverse_func,
119 static gint g_tree_node_post_order (GTreeNode *node,
120 GTraverseFunc traverse_func,
122 static gpointer g_tree_node_search (GTreeNode *node,
123 GCompareFunc search_func,
125 static GTreeNode* g_tree_node_rotate_left (GTreeNode *node);
126 static GTreeNode* g_tree_node_rotate_right (GTreeNode *node);
128 static void g_tree_node_check (GTreeNode *node);
133 g_tree_node_new (gpointer key,
136 GTreeNode *node = g_slice_new (GTreeNode);
141 node->left_child = FALSE;
142 node->right_child = FALSE;
151 * @key_compare_func: the function used to order the nodes in the #GTree.
152 * It should return values similar to the standard strcmp() function -
153 * 0 if the two arguments are equal, a negative value if the first argument
154 * comes before the second, or a positive value if the first argument comes
157 * Creates a new #GTree.
159 * Returns: a newly allocated #GTree
162 g_tree_new (GCompareFunc key_compare_func)
164 g_return_val_if_fail (key_compare_func != NULL, NULL);
166 return g_tree_new_full ((GCompareDataFunc) key_compare_func, NULL,
171 * g_tree_new_with_data:
172 * @key_compare_func: qsort()-style comparison function
173 * @key_compare_data: data to pass to comparison function
175 * Creates a new #GTree with a comparison function that accepts user data.
176 * See g_tree_new() for more details.
178 * Returns: a newly allocated #GTree
181 g_tree_new_with_data (GCompareDataFunc key_compare_func,
182 gpointer key_compare_data)
184 g_return_val_if_fail (key_compare_func != NULL, NULL);
186 return g_tree_new_full (key_compare_func, key_compare_data,
192 * @key_compare_func: qsort()-style comparison function
193 * @key_compare_data: data to pass to comparison function
194 * @key_destroy_func: a function to free the memory allocated for the key
195 * used when removing the entry from the #GTree or %NULL if you don't
196 * want to supply such a function
197 * @value_destroy_func: a function to free the memory allocated for the
198 * value used when removing the entry from the #GTree or %NULL if you
199 * don't want to supply such a function
201 * Creates a new #GTree like g_tree_new() and allows to specify functions
202 * to free the memory allocated for the key and value that get called when
203 * removing the entry from the #GTree.
205 * Returns: a newly allocated #GTree
208 g_tree_new_full (GCompareDataFunc key_compare_func,
209 gpointer key_compare_data,
210 GDestroyNotify key_destroy_func,
211 GDestroyNotify value_destroy_func)
215 g_return_val_if_fail (key_compare_func != NULL, NULL);
217 tree = g_slice_new (GTree);
219 tree->key_compare = key_compare_func;
220 tree->key_destroy_func = key_destroy_func;
221 tree->value_destroy_func = value_destroy_func;
222 tree->key_compare_data = key_compare_data;
229 static inline GTreeNode *
230 g_tree_first_node (GTree *tree)
239 while (tmp->left_child)
245 static inline GTreeNode *
246 g_tree_node_previous (GTreeNode *node)
252 if (node->left_child)
253 while (tmp->right_child)
259 static inline GTreeNode *
260 g_tree_node_next (GTreeNode *node)
266 if (node->right_child)
267 while (tmp->left_child)
274 g_tree_remove_all (GTree *tree)
279 g_return_if_fail (tree != NULL);
281 node = g_tree_first_node (tree);
285 next = g_tree_node_next (node);
287 if (tree->key_destroy_func)
288 tree->key_destroy_func (node->key);
289 if (tree->value_destroy_func)
290 tree->value_destroy_func (node->value);
291 g_slice_free (GTreeNode, node);
304 * Increments the reference count of @tree by one.
306 * It is safe to call this function from any thread.
308 * Returns: the passed in #GTree
313 g_tree_ref (GTree *tree)
315 g_return_val_if_fail (tree != NULL, NULL);
317 g_atomic_int_inc (&tree->ref_count);
326 * Decrements the reference count of @tree by one.
327 * If the reference count drops to 0, all keys and values will
328 * be destroyed (if destroy functions were specified) and all
329 * memory allocated by @tree will be released.
331 * It is safe to call this function from any thread.
336 g_tree_unref (GTree *tree)
338 g_return_if_fail (tree != NULL);
340 if (g_atomic_int_dec_and_test (&tree->ref_count))
342 g_tree_remove_all (tree);
343 g_slice_free (GTree, tree);
351 * Removes all keys and values from the #GTree and decreases its
352 * reference count by one. If keys and/or values are dynamically
353 * allocated, you should either free them first or create the #GTree
354 * using g_tree_new_full(). In the latter case the destroy functions
355 * you supplied will be called on all keys and values before destroying
359 g_tree_destroy (GTree *tree)
361 g_return_if_fail (tree != NULL);
363 g_tree_remove_all (tree);
370 * @key: the key to insert
371 * @value: the value corresponding to the key
373 * Inserts a key/value pair into a #GTree.
375 * If the given key already exists in the #GTree its corresponding value
376 * is set to the new value. If you supplied a @value_destroy_func when
377 * creating the #GTree, the old value is freed using that function. If
378 * you supplied a @key_destroy_func when creating the #GTree, the passed
379 * key is freed using that function.
381 * The tree is automatically 'balanced' as new key/value pairs are added,
382 * so that the distance from the root to every leaf is as small as possible.
385 g_tree_insert (GTree *tree,
389 g_return_if_fail (tree != NULL);
391 g_tree_insert_internal (tree, key, value, FALSE);
394 g_tree_node_check (tree->root);
401 * @key: the key to insert
402 * @value: the value corresponding to the key
404 * Inserts a new key and value into a #GTree similar to g_tree_insert().
405 * The difference is that if the key already exists in the #GTree, it gets
406 * replaced by the new key. If you supplied a @value_destroy_func when
407 * creating the #GTree, the old value is freed using that function. If you
408 * supplied a @key_destroy_func when creating the #GTree, the old key is
409 * freed using that function.
411 * The tree is automatically 'balanced' as new key/value pairs are added,
412 * so that the distance from the root to every leaf is as small as possible.
415 g_tree_replace (GTree *tree,
419 g_return_if_fail (tree != NULL);
421 g_tree_insert_internal (tree, key, value, TRUE);
424 g_tree_node_check (tree->root);
428 /* internal insert routine */
430 g_tree_insert_internal (GTree *tree,
436 GTreeNode *path[MAX_GTREE_HEIGHT];
439 g_return_if_fail (tree != NULL);
443 tree->root = g_tree_node_new (key, value);
454 int cmp = tree->key_compare (key, node->key, tree->key_compare_data);
458 if (tree->value_destroy_func)
459 tree->value_destroy_func (node->value);
465 if (tree->key_destroy_func)
466 tree->key_destroy_func (node->key);
472 /* free the passed key */
473 if (tree->key_destroy_func)
474 tree->key_destroy_func (key);
481 if (node->left_child)
488 GTreeNode *child = g_tree_node_new (key, value);
490 child->left = node->left;
493 node->left_child = TRUE;
503 if (node->right_child)
510 GTreeNode *child = g_tree_node_new (key, value);
512 child->right = node->right;
515 node->right_child = TRUE;
525 /* Restore balance. This is the goodness of a non-recursive
526 * implementation, when we are done with balancing we 'break'
527 * the loop and we are done.
531 GTreeNode *bparent = path[--idx];
532 gboolean left_node = (bparent && node == bparent->left);
533 g_assert (!bparent || bparent->left == node || bparent->right == node);
535 if (node->balance < -1 || node->balance > 1)
537 node = g_tree_node_balance (node);
541 bparent->left = node;
543 bparent->right = node;
546 if (node->balance == 0 || bparent == NULL)
550 bparent->balance -= 1;
552 bparent->balance += 1;
561 * @key: the key to remove
563 * Removes a key/value pair from a #GTree.
565 * If the #GTree was created using g_tree_new_full(), the key and value
566 * are freed using the supplied destroy functions, otherwise you have to
567 * make sure that any dynamically allocated values are freed yourself.
568 * If the key does not exist in the #GTree, the function does nothing.
570 * Returns: %TRUE if the key was found (prior to 2.8, this function
574 g_tree_remove (GTree *tree,
579 g_return_val_if_fail (tree != NULL, FALSE);
581 removed = g_tree_remove_internal (tree, key, FALSE);
584 g_tree_node_check (tree->root);
593 * @key: the key to remove
595 * Removes a key and its associated value from a #GTree without calling
596 * the key and value destroy functions.
598 * If the key does not exist in the #GTree, the function does nothing.
600 * Returns: %TRUE if the key was found (prior to 2.8, this function
604 g_tree_steal (GTree *tree,
609 g_return_val_if_fail (tree != NULL, FALSE);
611 removed = g_tree_remove_internal (tree, key, TRUE);
614 g_tree_node_check (tree->root);
620 /* internal remove routine */
622 g_tree_remove_internal (GTree *tree,
626 GTreeNode *node, *parent, *balance;
627 GTreeNode *path[MAX_GTREE_HEIGHT];
631 g_return_val_if_fail (tree != NULL, FALSE);
642 int cmp = tree->key_compare (key, node->key, tree->key_compare_data);
648 if (!node->left_child)
656 if (!node->right_child)
664 /* The following code is almost equal to g_tree_remove_node,
665 * except that we do not have to call g_tree_node_parent.
667 balance = parent = path[--idx];
668 g_assert (!parent || parent->left == node || parent->right == node);
669 left_node = (parent && node == parent->left);
671 if (!node->left_child)
673 if (!node->right_child)
679 parent->left_child = FALSE;
680 parent->left = node->left;
681 parent->balance += 1;
685 parent->right_child = FALSE;
686 parent->right = node->right;
687 parent->balance -= 1;
690 else /* node has a right child */
692 GTreeNode *tmp = g_tree_node_next (node);
693 tmp->left = node->left;
696 tree->root = node->right;
699 parent->left = node->right;
700 parent->balance += 1;
704 parent->right = node->right;
705 parent->balance -= 1;
709 else /* node has a left child */
711 if (!node->right_child)
713 GTreeNode *tmp = g_tree_node_previous (node);
714 tmp->right = node->right;
717 tree->root = node->left;
720 parent->left = node->left;
721 parent->balance += 1;
725 parent->right = node->left;
726 parent->balance -= 1;
729 else /* node has a both children (pant, pant!) */
731 GTreeNode *prev = node->left;
732 GTreeNode *next = node->right;
733 GTreeNode *nextp = node;
734 int old_idx = idx + 1;
737 /* path[idx] == parent */
738 /* find the immediately next node (and its parent) */
739 while (next->left_child)
741 path[++idx] = nextp = next;
745 path[old_idx] = next;
748 /* remove 'next' from the tree */
751 if (next->right_child)
752 nextp->left = next->right;
754 nextp->left_child = FALSE;
757 next->right_child = TRUE;
758 next->right = node->right;
763 /* set the prev to point to the right place */
764 while (prev->right_child)
768 /* prepare 'next' to replace 'node' */
769 next->left_child = TRUE;
770 next->left = node->left;
771 next->balance = node->balance;
778 parent->right = next;
782 /* restore balance */
786 GTreeNode *bparent = path[--idx];
787 g_assert (!bparent || bparent->left == balance || bparent->right == balance);
788 left_node = (bparent && balance == bparent->left);
790 if(balance->balance < -1 || balance->balance > 1)
792 balance = g_tree_node_balance (balance);
794 tree->root = balance;
796 bparent->left = balance;
798 bparent->right = balance;
801 if (balance->balance != 0 || !bparent)
805 bparent->balance += 1;
807 bparent->balance -= 1;
814 if (tree->key_destroy_func)
815 tree->key_destroy_func (node->key);
816 if (tree->value_destroy_func)
817 tree->value_destroy_func (node->value);
820 g_slice_free (GTreeNode, node);
830 * @key: the key to look up
832 * Gets the value corresponding to the given key. Since a #GTree is
833 * automatically balanced as key/value pairs are added, key lookup
834 * is O(log n) (where n is the number of key/value pairs in the tree).
836 * Returns: the value corresponding to the key, or %NULL
837 * if the key was not found
840 g_tree_lookup (GTree *tree,
845 g_return_val_if_fail (tree != NULL, NULL);
847 node = g_tree_find_node (tree, key);
849 return node ? node->value : NULL;
853 * g_tree_lookup_extended:
855 * @lookup_key: the key to look up
856 * @orig_key: returns the original key
857 * @value: returns the value associated with the key
859 * Looks up a key in the #GTree, returning the original key and the
860 * associated value. This is useful if you need to free the memory
861 * allocated for the original key, for example before calling
864 * Returns: %TRUE if the key was found in the #GTree
867 g_tree_lookup_extended (GTree *tree,
868 gconstpointer lookup_key,
874 g_return_val_if_fail (tree != NULL, FALSE);
876 node = g_tree_find_node (tree, lookup_key);
881 *orig_key = node->key;
883 *value = node->value;
893 * @func: the function to call for each node visited.
894 * If this function returns %TRUE, the traversal is stopped.
895 * @user_data: user data to pass to the function
897 * Calls the given function for each of the key/value pairs in the #GTree.
898 * The function is passed the key and value of each pair, and the given
899 * @data parameter. The tree is traversed in sorted order.
901 * The tree may not be modified while iterating over it (you can't
902 * add/remove items). To remove all items matching a predicate, you need
903 * to add each item to a list in your #GTraverseFunc as you walk over
904 * the tree, then walk the list and remove each item.
907 g_tree_foreach (GTree *tree,
913 g_return_if_fail (tree != NULL);
918 node = g_tree_first_node (tree);
922 if ((*func) (node->key, node->value, user_data))
925 node = g_tree_node_next (node);
932 * @traverse_func: the function to call for each node visited. If this
933 * function returns %TRUE, the traversal is stopped.
934 * @traverse_type: the order in which nodes are visited, one of %G_IN_ORDER,
935 * %G_PRE_ORDER and %G_POST_ORDER
936 * @user_data: user data to pass to the function
938 * Calls the given function for each node in the #GTree.
940 * Deprecated:2.2: The order of a balanced tree is somewhat arbitrary.
941 * If you just want to visit all nodes in sorted order, use
942 * g_tree_foreach() instead. If you really need to visit nodes in
943 * a different order, consider using an [n-ary tree][glib-N-ary-Trees].
947 * @key: a key of a #GTree node
948 * @value: the value corresponding to the key
949 * @data: user data passed to g_tree_traverse()
951 * Specifies the type of function passed to g_tree_traverse(). It is
952 * passed the key and value of each node, together with the @user_data
953 * parameter passed to g_tree_traverse(). If the function returns
954 * %TRUE, the traversal is stopped.
956 * Returns: %TRUE to stop the traversal
959 g_tree_traverse (GTree *tree,
960 GTraverseFunc traverse_func,
961 GTraverseType traverse_type,
964 g_return_if_fail (tree != NULL);
969 switch (traverse_type)
972 g_tree_node_pre_order (tree->root, traverse_func, user_data);
976 g_tree_node_in_order (tree->root, traverse_func, user_data);
980 g_tree_node_post_order (tree->root, traverse_func, user_data);
984 g_warning ("g_tree_traverse(): traverse type G_LEVEL_ORDER isn't implemented.");
992 * @search_func: a function used to search the #GTree
993 * @user_data: the data passed as the second argument to @search_func
995 * Searches a #GTree using @search_func.
997 * The @search_func is called with a pointer to the key of a key/value
998 * pair in the tree, and the passed in @user_data. If @search_func returns
999 * 0 for a key/value pair, then the corresponding value is returned as
1000 * the result of g_tree_search(). If @search_func returns -1, searching
1001 * will proceed among the key/value pairs that have a smaller key; if
1002 * @search_func returns 1, searching will proceed among the key/value
1003 * pairs that have a larger key.
1005 * Returns: the value corresponding to the found key, or %NULL
1006 * if the key was not found
1009 g_tree_search (GTree *tree,
1010 GCompareFunc search_func,
1011 gconstpointer user_data)
1013 g_return_val_if_fail (tree != NULL, NULL);
1016 return g_tree_node_search (tree->root, search_func, user_data);
1025 * Gets the height of a #GTree.
1027 * If the #GTree contains no nodes, the height is 0.
1028 * If the #GTree contains only one root node the height is 1.
1029 * If the root node has children the height is 2, etc.
1031 * Returns: the height of @tree
1034 g_tree_height (GTree *tree)
1039 g_return_val_if_fail (tree != NULL, 0);
1049 height += 1 + MAX(node->balance, 0);
1051 if (!node->left_child)
1062 * Gets the number of nodes in a #GTree.
1064 * Returns: the number of nodes in @tree
1067 g_tree_nnodes (GTree *tree)
1069 g_return_val_if_fail (tree != NULL, 0);
1071 return tree->nnodes;
1075 g_tree_node_balance (GTreeNode *node)
1077 if (node->balance < -1)
1079 if (node->left->balance > 0)
1080 node->left = g_tree_node_rotate_left (node->left);
1081 node = g_tree_node_rotate_right (node);
1083 else if (node->balance > 1)
1085 if (node->right->balance < 0)
1086 node->right = g_tree_node_rotate_right (node->right);
1087 node = g_tree_node_rotate_left (node);
1094 g_tree_find_node (GTree *tree,
1106 cmp = tree->key_compare (key, node->key, tree->key_compare_data);
1111 if (!node->left_child)
1118 if (!node->right_child)
1127 g_tree_node_pre_order (GTreeNode *node,
1128 GTraverseFunc traverse_func,
1131 if ((*traverse_func) (node->key, node->value, data))
1134 if (node->left_child)
1136 if (g_tree_node_pre_order (node->left, traverse_func, data))
1140 if (node->right_child)
1142 if (g_tree_node_pre_order (node->right, traverse_func, data))
1150 g_tree_node_in_order (GTreeNode *node,
1151 GTraverseFunc traverse_func,
1154 if (node->left_child)
1156 if (g_tree_node_in_order (node->left, traverse_func, data))
1160 if ((*traverse_func) (node->key, node->value, data))
1163 if (node->right_child)
1165 if (g_tree_node_in_order (node->right, traverse_func, data))
1173 g_tree_node_post_order (GTreeNode *node,
1174 GTraverseFunc traverse_func,
1177 if (node->left_child)
1179 if (g_tree_node_post_order (node->left, traverse_func, data))
1183 if (node->right_child)
1185 if (g_tree_node_post_order (node->right, traverse_func, data))
1189 if ((*traverse_func) (node->key, node->value, data))
1196 g_tree_node_search (GTreeNode *node,
1197 GCompareFunc search_func,
1207 dir = (* search_func) (node->key, data);
1212 if (!node->left_child)
1219 if (!node->right_child)
1228 g_tree_node_rotate_left (GTreeNode *node)
1234 right = node->right;
1236 if (right->left_child)
1237 node->right = right->left;
1240 node->right_child = FALSE;
1241 right->left_child = TRUE;
1245 a_bal = node->balance;
1246 b_bal = right->balance;
1251 right->balance = b_bal - 1;
1253 right->balance = a_bal + b_bal - 2;
1254 node->balance = a_bal - 1;
1259 right->balance = a_bal - 2;
1261 right->balance = b_bal - 1;
1262 node->balance = a_bal - b_bal - 1;
1269 g_tree_node_rotate_right (GTreeNode *node)
1277 if (left->right_child)
1278 node->left = left->right;
1281 node->left_child = FALSE;
1282 left->right_child = TRUE;
1286 a_bal = node->balance;
1287 b_bal = left->balance;
1292 left->balance = b_bal + 1;
1294 left->balance = a_bal + 2;
1295 node->balance = a_bal - b_bal + 1;
1300 left->balance = b_bal + 1;
1302 left->balance = a_bal + b_bal + 2;
1303 node->balance = a_bal + 1;
1311 g_tree_node_height (GTreeNode *node)
1321 if (node->left_child)
1322 left_height = g_tree_node_height (node->left);
1324 if (node->right_child)
1325 right_height = g_tree_node_height (node->right);
1327 return MAX (left_height, right_height) + 1;
1334 g_tree_node_check (GTreeNode *node)
1343 if (node->left_child)
1345 tmp = g_tree_node_previous (node);
1346 g_assert (tmp->right == node);
1349 if (node->right_child)
1351 tmp = g_tree_node_next (node);
1352 g_assert (tmp->left == node);
1358 if (node->left_child)
1359 left_height = g_tree_node_height (node->left);
1360 if (node->right_child)
1361 right_height = g_tree_node_height (node->right);
1363 balance = right_height - left_height;
1364 g_assert (balance == node->balance);
1366 if (node->left_child)
1367 g_tree_node_check (node->left);
1368 if (node->right_child)
1369 g_tree_node_check (node->right);
1374 g_tree_node_dump (GTreeNode *node,
1377 g_print ("%*s%c\n", indent, "", *(char *)node->key);
1379 if (node->left_child)
1380 g_tree_node_dump (node->left, indent + 2);
1381 else if (node->left)
1382 g_print ("%*s<%c\n", indent + 2, "", *(char *)node->left->key);
1384 if (node->right_child)
1385 g_tree_node_dump (node->right, indent + 2);
1386 else if (node->right)
1387 g_print ("%*s>%c\n", indent + 2, "", *(char *)node->right->key);
1392 g_tree_dump (GTree *tree)
1395 g_tree_node_dump (tree->root, 0);