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, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
36 #include "gtestutils.h"
40 * SECTION:trees-binary
41 * @title: Balanced Binary Trees
42 * @short_description: a sorted collection of key/value pairs optimized
43 * for searching and traversing in order
45 * The #GTree structure and its associated functions provide a sorted
46 * collection of key/value pairs optimized for searching and traversing
49 * To create a new #GTree use g_tree_new().
51 * To insert a key/value pair into a #GTree use g_tree_insert().
53 * To lookup the value corresponding to a given key, use
54 * g_tree_lookup() and g_tree_lookup_extended().
56 * To find out the number of nodes in a #GTree, use g_tree_nnodes(). To
57 * get the height of a #GTree, use g_tree_height().
59 * To traverse a #GTree, calling a function for each node visited in
60 * the traversal, use g_tree_foreach().
62 * To remove a key/value pair use g_tree_remove().
64 * To destroy a #GTree, use g_tree_destroy().
69 #define MAX_GTREE_HEIGHT 40
71 typedef struct _GTreeNode GTreeNode;
76 * The <structname>GTree</structname> struct is an opaque data
77 * structure representing a <link
78 * linkend="glib-Balanced-Binary-Trees">Balanced Binary Tree</link>. It
79 * should be accessed only by using the following functions.
84 GCompareDataFunc key_compare;
85 GDestroyNotify key_destroy_func;
86 GDestroyNotify value_destroy_func;
87 gpointer key_compare_data;
94 gpointer key; /* key for this node */
95 gpointer value; /* value stored at this node */
96 GTreeNode *left; /* left subtree */
97 GTreeNode *right; /* right subtree */
98 gint8 balance; /* height (right) - height (left) */
104 static GTreeNode* g_tree_node_new (gpointer key,
106 static void g_tree_insert_internal (GTree *tree,
110 static gboolean g_tree_remove_internal (GTree *tree,
113 static GTreeNode* g_tree_node_balance (GTreeNode *node);
114 static GTreeNode *g_tree_find_node (GTree *tree,
116 static gint g_tree_node_pre_order (GTreeNode *node,
117 GTraverseFunc traverse_func,
119 static gint g_tree_node_in_order (GTreeNode *node,
120 GTraverseFunc traverse_func,
122 static gint g_tree_node_post_order (GTreeNode *node,
123 GTraverseFunc traverse_func,
125 static gpointer g_tree_node_search (GTreeNode *node,
126 GCompareFunc search_func,
128 static GTreeNode* g_tree_node_rotate_left (GTreeNode *node);
129 static GTreeNode* g_tree_node_rotate_right (GTreeNode *node);
131 static void g_tree_node_check (GTreeNode *node);
136 g_tree_node_new (gpointer key,
139 GTreeNode *node = g_slice_new (GTreeNode);
144 node->left_child = FALSE;
145 node->right_child = FALSE;
154 * @key_compare_func: the function used to order the nodes in the #GTree.
155 * It should return values similar to the standard strcmp() function -
156 * 0 if the two arguments are equal, a negative value if the first argument
157 * comes before the second, or a positive value if the first argument comes
160 * Creates a new #GTree.
162 * Return value: a newly allocated #GTree
165 g_tree_new (GCompareFunc key_compare_func)
167 g_return_val_if_fail (key_compare_func != NULL, NULL);
169 return g_tree_new_full ((GCompareDataFunc) key_compare_func, NULL,
174 * g_tree_new_with_data:
175 * @key_compare_func: qsort()-style comparison function
176 * @key_compare_data: data to pass to comparison function
178 * Creates a new #GTree with a comparison function that accepts user data.
179 * See g_tree_new() for more details.
181 * Return value: a newly allocated #GTree
184 g_tree_new_with_data (GCompareDataFunc key_compare_func,
185 gpointer key_compare_data)
187 g_return_val_if_fail (key_compare_func != NULL, NULL);
189 return g_tree_new_full (key_compare_func, key_compare_data,
195 * @key_compare_func: qsort()-style comparison function
196 * @key_compare_data: data to pass to comparison function
197 * @key_destroy_func: a function to free the memory allocated for the key
198 * used when removing the entry from the #GTree or %NULL if you don't
199 * want to supply such a function
200 * @value_destroy_func: a function to free the memory allocated for the
201 * value used when removing the entry from the #GTree or %NULL if you
202 * don't want to supply such a function
204 * Creates a new #GTree like g_tree_new() and allows to specify functions
205 * to free the memory allocated for the key and value that get called when
206 * removing the entry from the #GTree.
208 * Return value: a newly allocated #GTree
211 g_tree_new_full (GCompareDataFunc key_compare_func,
212 gpointer key_compare_data,
213 GDestroyNotify key_destroy_func,
214 GDestroyNotify value_destroy_func)
218 g_return_val_if_fail (key_compare_func != NULL, NULL);
220 tree = g_slice_new (GTree);
222 tree->key_compare = key_compare_func;
223 tree->key_destroy_func = key_destroy_func;
224 tree->value_destroy_func = value_destroy_func;
225 tree->key_compare_data = key_compare_data;
232 static inline GTreeNode *
233 g_tree_first_node (GTree *tree)
242 while (tmp->left_child)
248 static inline GTreeNode *
249 g_tree_node_previous (GTreeNode *node)
255 if (node->left_child)
256 while (tmp->right_child)
262 static inline GTreeNode *
263 g_tree_node_next (GTreeNode *node)
269 if (node->right_child)
270 while (tmp->left_child)
277 g_tree_remove_all (GTree *tree)
282 g_return_if_fail (tree != NULL);
284 node = g_tree_first_node (tree);
288 next = g_tree_node_next (node);
290 if (tree->key_destroy_func)
291 tree->key_destroy_func (node->key);
292 if (tree->value_destroy_func)
293 tree->value_destroy_func (node->value);
294 g_slice_free (GTreeNode, node);
307 * Increments the reference count of @tree by one.
309 * It is safe to call this function from any thread.
311 * Return value: the passed in #GTree
316 g_tree_ref (GTree *tree)
318 g_return_val_if_fail (tree != NULL, NULL);
320 g_atomic_int_inc (&tree->ref_count);
329 * Decrements the reference count of @tree by one.
330 * If the reference count drops to 0, all keys and values will
331 * be destroyed (if destroy functions were specified) and all
332 * memory allocated by @tree will be released.
334 * It is safe to call this function from any thread.
339 g_tree_unref (GTree *tree)
341 g_return_if_fail (tree != NULL);
343 if (g_atomic_int_dec_and_test (&tree->ref_count))
345 g_tree_remove_all (tree);
346 g_slice_free (GTree, tree);
354 * Removes all keys and values from the #GTree and decreases its
355 * reference count by one. If keys and/or values are dynamically
356 * allocated, you should either free them first or create the #GTree
357 * using g_tree_new_full(). In the latter case the destroy functions
358 * you supplied will be called on all keys and values before destroying
362 g_tree_destroy (GTree *tree)
364 g_return_if_fail (tree != NULL);
366 g_tree_remove_all (tree);
373 * @key: the key to insert
374 * @value: the value corresponding to the key
376 * Inserts a key/value pair into a #GTree.
378 * If the given key already exists in the #GTree its corresponding value
379 * is set to the new value. If you supplied a @value_destroy_func when
380 * creating the #GTree, the old value is freed using that function. If
381 * you supplied a @key_destroy_func when creating the #GTree, the passed
382 * key is freed using that function.
384 * The tree is automatically 'balanced' as new key/value pairs are added,
385 * so that the distance from the root to every leaf is as small as possible.
388 g_tree_insert (GTree *tree,
392 g_return_if_fail (tree != NULL);
394 g_tree_insert_internal (tree, key, value, FALSE);
397 g_tree_node_check (tree->root);
404 * @key: the key to insert
405 * @value: the value corresponding to the key
407 * Inserts a new key and value into a #GTree similar to g_tree_insert().
408 * The difference is that if the key already exists in the #GTree, it gets
409 * replaced by the new key. If you supplied a @value_destroy_func when
410 * creating the #GTree, the old value is freed using that function. If you
411 * supplied a @key_destroy_func when creating the #GTree, the old key is
412 * freed using that function.
414 * The tree is automatically 'balanced' as new key/value pairs are added,
415 * so that the distance from the root to every leaf is as small as possible.
418 g_tree_replace (GTree *tree,
422 g_return_if_fail (tree != NULL);
424 g_tree_insert_internal (tree, key, value, TRUE);
427 g_tree_node_check (tree->root);
431 /* internal insert routine */
433 g_tree_insert_internal (GTree *tree,
439 GTreeNode *path[MAX_GTREE_HEIGHT];
442 g_return_if_fail (tree != NULL);
446 tree->root = g_tree_node_new (key, value);
457 int cmp = tree->key_compare (key, node->key, tree->key_compare_data);
461 if (tree->value_destroy_func)
462 tree->value_destroy_func (node->value);
468 if (tree->key_destroy_func)
469 tree->key_destroy_func (node->key);
475 /* free the passed key */
476 if (tree->key_destroy_func)
477 tree->key_destroy_func (key);
484 if (node->left_child)
491 GTreeNode *child = g_tree_node_new (key, value);
493 child->left = node->left;
496 node->left_child = TRUE;
506 if (node->right_child)
513 GTreeNode *child = g_tree_node_new (key, value);
515 child->right = node->right;
518 node->right_child = TRUE;
528 /* Restore balance. This is the goodness of a non-recursive
529 * implementation, when we are done with balancing we 'break'
530 * the loop and we are done.
534 GTreeNode *bparent = path[--idx];
535 gboolean left_node = (bparent && node == bparent->left);
536 g_assert (!bparent || bparent->left == node || bparent->right == node);
538 if (node->balance < -1 || node->balance > 1)
540 node = g_tree_node_balance (node);
544 bparent->left = node;
546 bparent->right = node;
549 if (node->balance == 0 || bparent == NULL)
553 bparent->balance -= 1;
555 bparent->balance += 1;
564 * @key: the key to remove
566 * Removes a key/value pair from a #GTree.
568 * If the #GTree was created using g_tree_new_full(), the key and value
569 * are freed using the supplied destroy functions, otherwise you have to
570 * make sure that any dynamically allocated values are freed yourself.
571 * If the key does not exist in the #GTree, the function does nothing.
573 * Returns: %TRUE if the key was found (prior to 2.8, this function
577 g_tree_remove (GTree *tree,
582 g_return_val_if_fail (tree != NULL, FALSE);
584 removed = g_tree_remove_internal (tree, key, FALSE);
587 g_tree_node_check (tree->root);
596 * @key: the key to remove
598 * Removes a key and its associated value from a #GTree without calling
599 * the key and value destroy functions.
601 * If the key does not exist in the #GTree, the function does nothing.
603 * Returns: %TRUE if the key was found (prior to 2.8, this function
607 g_tree_steal (GTree *tree,
612 g_return_val_if_fail (tree != NULL, FALSE);
614 removed = g_tree_remove_internal (tree, key, TRUE);
617 g_tree_node_check (tree->root);
623 /* internal remove routine */
625 g_tree_remove_internal (GTree *tree,
629 GTreeNode *node, *parent, *balance;
630 GTreeNode *path[MAX_GTREE_HEIGHT];
634 g_return_val_if_fail (tree != NULL, FALSE);
645 int cmp = tree->key_compare (key, node->key, tree->key_compare_data);
651 if (!node->left_child)
659 if (!node->right_child)
667 /* The following code is almost equal to g_tree_remove_node,
668 * except that we do not have to call g_tree_node_parent.
670 balance = parent = path[--idx];
671 g_assert (!parent || parent->left == node || parent->right == node);
672 left_node = (parent && node == parent->left);
674 if (!node->left_child)
676 if (!node->right_child)
682 parent->left_child = FALSE;
683 parent->left = node->left;
684 parent->balance += 1;
688 parent->right_child = FALSE;
689 parent->right = node->right;
690 parent->balance -= 1;
693 else /* node has a right child */
695 GTreeNode *tmp = g_tree_node_next (node);
696 tmp->left = node->left;
699 tree->root = node->right;
702 parent->left = node->right;
703 parent->balance += 1;
707 parent->right = node->right;
708 parent->balance -= 1;
712 else /* node has a left child */
714 if (!node->right_child)
716 GTreeNode *tmp = g_tree_node_previous (node);
717 tmp->right = node->right;
720 tree->root = node->left;
723 parent->left = node->left;
724 parent->balance += 1;
728 parent->right = node->left;
729 parent->balance -= 1;
732 else /* node has a both children (pant, pant!) */
734 GTreeNode *prev = node->left;
735 GTreeNode *next = node->right;
736 GTreeNode *nextp = node;
737 int old_idx = idx + 1;
740 /* path[idx] == parent */
741 /* find the immediately next node (and its parent) */
742 while (next->left_child)
744 path[++idx] = nextp = next;
748 path[old_idx] = next;
751 /* remove 'next' from the tree */
754 if (next->right_child)
755 nextp->left = next->right;
757 nextp->left_child = FALSE;
760 next->right_child = TRUE;
761 next->right = node->right;
766 /* set the prev to point to the right place */
767 while (prev->right_child)
771 /* prepare 'next' to replace 'node' */
772 next->left_child = TRUE;
773 next->left = node->left;
774 next->balance = node->balance;
781 parent->right = next;
785 /* restore balance */
789 GTreeNode *bparent = path[--idx];
790 g_assert (!bparent || bparent->left == balance || bparent->right == balance);
791 left_node = (bparent && balance == bparent->left);
793 if(balance->balance < -1 || balance->balance > 1)
795 balance = g_tree_node_balance (balance);
797 tree->root = balance;
799 bparent->left = balance;
801 bparent->right = balance;
804 if (balance->balance != 0 || !bparent)
808 bparent->balance += 1;
810 bparent->balance -= 1;
817 if (tree->key_destroy_func)
818 tree->key_destroy_func (node->key);
819 if (tree->value_destroy_func)
820 tree->value_destroy_func (node->value);
823 g_slice_free (GTreeNode, node);
833 * @key: the key to look up
835 * Gets the value corresponding to the given key. Since a #GTree is
836 * automatically balanced as key/value pairs are added, key lookup
837 * is O(log n) (where n is the number of key/value pairs in the tree).
839 * Return value: the value corresponding to the key, or %NULL
840 * if the key was not found.
843 g_tree_lookup (GTree *tree,
848 g_return_val_if_fail (tree != NULL, NULL);
850 node = g_tree_find_node (tree, key);
852 return node ? node->value : NULL;
856 * g_tree_lookup_extended:
858 * @lookup_key: the key to look up
859 * @orig_key: returns the original key
860 * @value: returns the value associated with the key
862 * Looks up a key in the #GTree, returning the original key and the
863 * associated value. This is useful if you need to free the memory
864 * allocated for the original key, for example before calling
867 * Return value: %TRUE if the key was found in the #GTree
870 g_tree_lookup_extended (GTree *tree,
871 gconstpointer lookup_key,
877 g_return_val_if_fail (tree != NULL, FALSE);
879 node = g_tree_find_node (tree, lookup_key);
884 *orig_key = node->key;
886 *value = node->value;
896 * @func: the function to call for each node visited.
897 * If this function returns %TRUE, the traversal is stopped.
898 * @user_data: user data to pass to the function
900 * Calls the given function for each of the key/value pairs in the #GTree.
901 * The function is passed the key and value of each pair, and the given
902 * @data parameter. The tree is traversed in sorted order.
904 * The tree may not be modified while iterating over it (you can't
905 * add/remove items). To remove all items matching a predicate, you need
906 * to add each item to a list in your #GTraverseFunc as you walk over
907 * the tree, then walk the list and remove each item.
910 g_tree_foreach (GTree *tree,
916 g_return_if_fail (tree != NULL);
921 node = g_tree_first_node (tree);
925 if ((*func) (node->key, node->value, user_data))
928 node = g_tree_node_next (node);
935 * @traverse_func: the function to call for each node visited. If this
936 * function returns %TRUE, the traversal is stopped.
937 * @traverse_type: the order in which nodes are visited, one of %G_IN_ORDER,
938 * %G_PRE_ORDER and %G_POST_ORDER
939 * @user_data: user data to pass to the function
941 * Calls the given function for each node in the #GTree.
943 * Deprecated:2.2: The order of a balanced tree is somewhat arbitrary.
944 * If you just want to visit all nodes in sorted order, use
945 * g_tree_foreach() instead. If you really need to visit nodes in
946 * a different order, consider using an
947 * <link linkend="glib-N-ary-Trees">N-ary Tree</link>.
951 * @key: a key of a #GTree node
952 * @value: the value corresponding to the key
953 * @data: user data passed to g_tree_traverse()
955 * Specifies the type of function passed to g_tree_traverse(). It is
956 * passed the key and value of each node, together with the @user_data
957 * parameter passed to g_tree_traverse(). If the function returns
958 * %TRUE, the traversal is stopped.
960 * Returns: %TRUE to stop the traversal
963 g_tree_traverse (GTree *tree,
964 GTraverseFunc traverse_func,
965 GTraverseType traverse_type,
968 g_return_if_fail (tree != NULL);
973 switch (traverse_type)
976 g_tree_node_pre_order (tree->root, traverse_func, user_data);
980 g_tree_node_in_order (tree->root, traverse_func, user_data);
984 g_tree_node_post_order (tree->root, traverse_func, user_data);
988 g_warning ("g_tree_traverse(): traverse type G_LEVEL_ORDER isn't implemented.");
996 * @search_func: a function used to search the #GTree
997 * @user_data: the data passed as the second argument to @search_func
999 * Searches a #GTree using @search_func.
1001 * The @search_func is called with a pointer to the key of a key/value
1002 * pair in the tree, and the passed in @user_data. If @search_func returns
1003 * 0 for a key/value pair, then the corresponding value is returned as
1004 * the result of g_tree_search(). If @search_func returns -1, searching
1005 * will proceed among the key/value pairs that have a smaller key; if
1006 * @search_func returns 1, searching will proceed among the key/value
1007 * pairs that have a larger key.
1009 * Return value: the value corresponding to the found key, or %NULL
1010 * if the key was not found.
1013 g_tree_search (GTree *tree,
1014 GCompareFunc search_func,
1015 gconstpointer user_data)
1017 g_return_val_if_fail (tree != NULL, NULL);
1020 return g_tree_node_search (tree->root, search_func, user_data);
1029 * Gets the height of a #GTree.
1031 * If the #GTree contains no nodes, the height is 0.
1032 * If the #GTree contains only one root node the height is 1.
1033 * If the root node has children the height is 2, etc.
1035 * Return value: the height of @tree
1038 g_tree_height (GTree *tree)
1043 g_return_val_if_fail (tree != NULL, 0);
1053 height += 1 + MAX(node->balance, 0);
1055 if (!node->left_child)
1066 * Gets the number of nodes in a #GTree.
1068 * Return value: the number of nodes in @tree
1071 g_tree_nnodes (GTree *tree)
1073 g_return_val_if_fail (tree != NULL, 0);
1075 return tree->nnodes;
1079 g_tree_node_balance (GTreeNode *node)
1081 if (node->balance < -1)
1083 if (node->left->balance > 0)
1084 node->left = g_tree_node_rotate_left (node->left);
1085 node = g_tree_node_rotate_right (node);
1087 else if (node->balance > 1)
1089 if (node->right->balance < 0)
1090 node->right = g_tree_node_rotate_right (node->right);
1091 node = g_tree_node_rotate_left (node);
1098 g_tree_find_node (GTree *tree,
1110 cmp = tree->key_compare (key, node->key, tree->key_compare_data);
1115 if (!node->left_child)
1122 if (!node->right_child)
1131 g_tree_node_pre_order (GTreeNode *node,
1132 GTraverseFunc traverse_func,
1135 if ((*traverse_func) (node->key, node->value, data))
1138 if (node->left_child)
1140 if (g_tree_node_pre_order (node->left, traverse_func, data))
1144 if (node->right_child)
1146 if (g_tree_node_pre_order (node->right, traverse_func, data))
1154 g_tree_node_in_order (GTreeNode *node,
1155 GTraverseFunc traverse_func,
1158 if (node->left_child)
1160 if (g_tree_node_in_order (node->left, traverse_func, data))
1164 if ((*traverse_func) (node->key, node->value, data))
1167 if (node->right_child)
1169 if (g_tree_node_in_order (node->right, traverse_func, data))
1177 g_tree_node_post_order (GTreeNode *node,
1178 GTraverseFunc traverse_func,
1181 if (node->left_child)
1183 if (g_tree_node_post_order (node->left, traverse_func, data))
1187 if (node->right_child)
1189 if (g_tree_node_post_order (node->right, traverse_func, data))
1193 if ((*traverse_func) (node->key, node->value, data))
1200 g_tree_node_search (GTreeNode *node,
1201 GCompareFunc search_func,
1211 dir = (* search_func) (node->key, data);
1216 if (!node->left_child)
1223 if (!node->right_child)
1232 g_tree_node_rotate_left (GTreeNode *node)
1238 right = node->right;
1240 if (right->left_child)
1241 node->right = right->left;
1244 node->right_child = FALSE;
1245 right->left_child = TRUE;
1249 a_bal = node->balance;
1250 b_bal = right->balance;
1255 right->balance = b_bal - 1;
1257 right->balance = a_bal + b_bal - 2;
1258 node->balance = a_bal - 1;
1263 right->balance = a_bal - 2;
1265 right->balance = b_bal - 1;
1266 node->balance = a_bal - b_bal - 1;
1273 g_tree_node_rotate_right (GTreeNode *node)
1281 if (left->right_child)
1282 node->left = left->right;
1285 node->left_child = FALSE;
1286 left->right_child = TRUE;
1290 a_bal = node->balance;
1291 b_bal = left->balance;
1296 left->balance = b_bal + 1;
1298 left->balance = a_bal + 2;
1299 node->balance = a_bal - b_bal + 1;
1304 left->balance = b_bal + 1;
1306 left->balance = a_bal + b_bal + 2;
1307 node->balance = a_bal + 1;
1315 g_tree_node_height (GTreeNode *node)
1325 if (node->left_child)
1326 left_height = g_tree_node_height (node->left);
1328 if (node->right_child)
1329 right_height = g_tree_node_height (node->right);
1331 return MAX (left_height, right_height) + 1;
1338 g_tree_node_check (GTreeNode *node)
1347 if (node->left_child)
1349 tmp = g_tree_node_previous (node);
1350 g_assert (tmp->right == node);
1353 if (node->right_child)
1355 tmp = g_tree_node_next (node);
1356 g_assert (tmp->left == node);
1362 if (node->left_child)
1363 left_height = g_tree_node_height (node->left);
1364 if (node->right_child)
1365 right_height = g_tree_node_height (node->right);
1367 balance = right_height - left_height;
1368 g_assert (balance == node->balance);
1370 if (node->left_child)
1371 g_tree_node_check (node->left);
1372 if (node->right_child)
1373 g_tree_node_check (node->right);
1378 g_tree_node_dump (GTreeNode *node,
1381 g_print ("%*s%c\n", indent, "", *(char *)node->key);
1383 if (node->left_child)
1384 g_tree_node_dump (node->left, indent + 2);
1385 else if (node->left)
1386 g_print ("%*s<%c\n", indent + 2, "", *(char *)node->left->key);
1388 if (node->right_child)
1389 g_tree_node_dump (node->right, indent + 2);
1390 else if (node->right)
1391 g_print ("%*s>%c\n", indent + 2, "", *(char *)node->right->key);
1396 g_tree_dump (GTree *tree)
1399 g_tree_node_dump (tree->root, 0);