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 #GTree-struct is an opaque data structure representing a <link
77 * linkend="glib-Balanced-Binary-Trees">Balanced Binary Tree</link>.
78 * It should be accessed only by using the following functions.
83 GCompareDataFunc key_compare;
84 GDestroyNotify key_destroy_func;
85 GDestroyNotify value_destroy_func;
86 gpointer key_compare_data;
93 gpointer key; /* key for this node */
94 gpointer value; /* value stored at this node */
95 GTreeNode *left; /* left subtree */
96 GTreeNode *right; /* right subtree */
97 gint8 balance; /* height (right) - height (left) */
103 static GTreeNode* g_tree_node_new (gpointer key,
105 static void g_tree_insert_internal (GTree *tree,
109 static gboolean g_tree_remove_internal (GTree *tree,
112 static GTreeNode* g_tree_node_balance (GTreeNode *node);
113 static GTreeNode *g_tree_find_node (GTree *tree,
115 static gint g_tree_node_pre_order (GTreeNode *node,
116 GTraverseFunc traverse_func,
118 static gint g_tree_node_in_order (GTreeNode *node,
119 GTraverseFunc traverse_func,
121 static gint g_tree_node_post_order (GTreeNode *node,
122 GTraverseFunc traverse_func,
124 static gpointer g_tree_node_search (GTreeNode *node,
125 GCompareFunc search_func,
127 static GTreeNode* g_tree_node_rotate_left (GTreeNode *node);
128 static GTreeNode* g_tree_node_rotate_right (GTreeNode *node);
130 static void g_tree_node_check (GTreeNode *node);
135 g_tree_node_new (gpointer key,
138 GTreeNode *node = g_slice_new (GTreeNode);
143 node->left_child = FALSE;
144 node->right_child = FALSE;
153 * @key_compare_func: the function used to order the nodes in the #GTree.
154 * It should return values similar to the standard strcmp() function -
155 * 0 if the two arguments are equal, a negative value if the first argument
156 * comes before the second, or a positive value if the first argument comes
159 * Creates a new #GTree.
161 * Return value: a newly allocated #GTree
164 g_tree_new (GCompareFunc key_compare_func)
166 g_return_val_if_fail (key_compare_func != NULL, NULL);
168 return g_tree_new_full ((GCompareDataFunc) key_compare_func, NULL,
173 * g_tree_new_with_data:
174 * @key_compare_func: qsort()-style comparison function
175 * @key_compare_data: data to pass to comparison function
177 * Creates a new #GTree with a comparison function that accepts user data.
178 * See g_tree_new() for more details.
180 * Return value: a newly allocated #GTree
183 g_tree_new_with_data (GCompareDataFunc key_compare_func,
184 gpointer key_compare_data)
186 g_return_val_if_fail (key_compare_func != NULL, NULL);
188 return g_tree_new_full (key_compare_func, key_compare_data,
194 * @key_compare_func: qsort()-style comparison function
195 * @key_compare_data: data to pass to comparison function
196 * @key_destroy_func: a function to free the memory allocated for the key
197 * used when removing the entry from the #GTree or %NULL if you don't
198 * want to supply such a function
199 * @value_destroy_func: a function to free the memory allocated for the
200 * value used when removing the entry from the #GTree or %NULL if you
201 * don't want to supply such a function
203 * Creates a new #GTree like g_tree_new() and allows to specify functions
204 * to free the memory allocated for the key and value that get called when
205 * removing the entry from the #GTree.
207 * Return value: a newly allocated #GTree
210 g_tree_new_full (GCompareDataFunc key_compare_func,
211 gpointer key_compare_data,
212 GDestroyNotify key_destroy_func,
213 GDestroyNotify value_destroy_func)
217 g_return_val_if_fail (key_compare_func != NULL, NULL);
219 tree = g_slice_new (GTree);
221 tree->key_compare = key_compare_func;
222 tree->key_destroy_func = key_destroy_func;
223 tree->value_destroy_func = value_destroy_func;
224 tree->key_compare_data = key_compare_data;
231 static inline GTreeNode *
232 g_tree_first_node (GTree *tree)
241 while (tmp->left_child)
247 static inline GTreeNode *
248 g_tree_node_previous (GTreeNode *node)
254 if (node->left_child)
255 while (tmp->right_child)
261 static inline GTreeNode *
262 g_tree_node_next (GTreeNode *node)
268 if (node->right_child)
269 while (tmp->left_child)
276 g_tree_remove_all (GTree *tree)
281 g_return_if_fail (tree != NULL);
283 node = g_tree_first_node (tree);
287 next = g_tree_node_next (node);
289 if (tree->key_destroy_func)
290 tree->key_destroy_func (node->key);
291 if (tree->value_destroy_func)
292 tree->value_destroy_func (node->value);
293 g_slice_free (GTreeNode, node);
306 * Increments the reference count of @tree by one.
308 * It is safe to call this function from any thread.
310 * Return value: the passed in #GTree
315 g_tree_ref (GTree *tree)
317 g_return_val_if_fail (tree != NULL, NULL);
319 g_atomic_int_inc (&tree->ref_count);
328 * Decrements the reference count of @tree by one.
329 * If the reference count drops to 0, all keys and values will
330 * be destroyed (if destroy functions were specified) and all
331 * memory allocated by @tree will be released.
333 * It is safe to call this function from any thread.
338 g_tree_unref (GTree *tree)
340 g_return_if_fail (tree != NULL);
342 if (g_atomic_int_dec_and_test (&tree->ref_count))
344 g_tree_remove_all (tree);
345 g_slice_free (GTree, tree);
353 * Removes all keys and values from the #GTree and decreases its
354 * reference count by one. If keys and/or values are dynamically
355 * allocated, you should either free them first or create the #GTree
356 * using g_tree_new_full(). In the latter case the destroy functions
357 * you supplied will be called on all keys and values before destroying
361 g_tree_destroy (GTree *tree)
363 g_return_if_fail (tree != NULL);
365 g_tree_remove_all (tree);
372 * @key: the key to insert
373 * @value: the value corresponding to the key
375 * Inserts a key/value pair into a #GTree.
377 * If the given key already exists in the #GTree its corresponding value
378 * is set to the new value. If you supplied a @value_destroy_func when
379 * creating the #GTree, the old value is freed using that function. If
380 * you supplied a @key_destroy_func when creating the #GTree, the passed
381 * key is freed using that function.
383 * The tree is automatically 'balanced' as new key/value pairs are added,
384 * so that the distance from the root to every leaf is as small as possible.
387 g_tree_insert (GTree *tree,
391 g_return_if_fail (tree != NULL);
393 g_tree_insert_internal (tree, key, value, FALSE);
396 g_tree_node_check (tree->root);
403 * @key: the key to insert
404 * @value: the value corresponding to the key
406 * Inserts a new key and value into a #GTree similar to g_tree_insert().
407 * The difference is that if the key already exists in the #GTree, it gets
408 * replaced by the new key. If you supplied a @value_destroy_func when
409 * creating the #GTree, the old value is freed using that function. If you
410 * supplied a @key_destroy_func when creating the #GTree, the old key is
411 * freed using that function.
413 * The tree is automatically 'balanced' as new key/value pairs are added,
414 * so that the distance from the root to every leaf is as small as possible.
417 g_tree_replace (GTree *tree,
421 g_return_if_fail (tree != NULL);
423 g_tree_insert_internal (tree, key, value, TRUE);
426 g_tree_node_check (tree->root);
430 /* internal insert routine */
432 g_tree_insert_internal (GTree *tree,
438 GTreeNode *path[MAX_GTREE_HEIGHT];
441 g_return_if_fail (tree != NULL);
445 tree->root = g_tree_node_new (key, value);
456 int cmp = tree->key_compare (key, node->key, tree->key_compare_data);
460 if (tree->value_destroy_func)
461 tree->value_destroy_func (node->value);
467 if (tree->key_destroy_func)
468 tree->key_destroy_func (node->key);
474 /* free the passed key */
475 if (tree->key_destroy_func)
476 tree->key_destroy_func (key);
483 if (node->left_child)
490 GTreeNode *child = g_tree_node_new (key, value);
492 child->left = node->left;
495 node->left_child = TRUE;
505 if (node->right_child)
512 GTreeNode *child = g_tree_node_new (key, value);
514 child->right = node->right;
517 node->right_child = TRUE;
527 /* Restore balance. This is the goodness of a non-recursive
528 * implementation, when we are done with balancing we 'break'
529 * the loop and we are done.
533 GTreeNode *bparent = path[--idx];
534 gboolean left_node = (bparent && node == bparent->left);
535 g_assert (!bparent || bparent->left == node || bparent->right == node);
537 if (node->balance < -1 || node->balance > 1)
539 node = g_tree_node_balance (node);
543 bparent->left = node;
545 bparent->right = node;
548 if (node->balance == 0 || bparent == NULL)
552 bparent->balance -= 1;
554 bparent->balance += 1;
563 * @key: the key to remove
565 * Removes a key/value pair from a #GTree.
567 * If the #GTree was created using g_tree_new_full(), the key and value
568 * are freed using the supplied destroy functions, otherwise you have to
569 * make sure that any dynamically allocated values are freed yourself.
570 * If the key does not exist in the #GTree, the function does nothing.
572 * Returns: %TRUE if the key was found (prior to 2.8, this function
576 g_tree_remove (GTree *tree,
581 g_return_val_if_fail (tree != NULL, FALSE);
583 removed = g_tree_remove_internal (tree, key, FALSE);
586 g_tree_node_check (tree->root);
595 * @key: the key to remove
597 * Removes a key and its associated value from a #GTree without calling
598 * the key and value destroy functions.
600 * If the key does not exist in the #GTree, the function does nothing.
602 * Returns: %TRUE if the key was found (prior to 2.8, this function
606 g_tree_steal (GTree *tree,
611 g_return_val_if_fail (tree != NULL, FALSE);
613 removed = g_tree_remove_internal (tree, key, TRUE);
616 g_tree_node_check (tree->root);
622 /* internal remove routine */
624 g_tree_remove_internal (GTree *tree,
628 GTreeNode *node, *parent, *balance;
629 GTreeNode *path[MAX_GTREE_HEIGHT];
633 g_return_val_if_fail (tree != NULL, FALSE);
644 int cmp = tree->key_compare (key, node->key, tree->key_compare_data);
650 if (!node->left_child)
658 if (!node->right_child)
666 /* The following code is almost equal to g_tree_remove_node,
667 * except that we do not have to call g_tree_node_parent.
669 balance = parent = path[--idx];
670 g_assert (!parent || parent->left == node || parent->right == node);
671 left_node = (parent && node == parent->left);
673 if (!node->left_child)
675 if (!node->right_child)
681 parent->left_child = FALSE;
682 parent->left = node->left;
683 parent->balance += 1;
687 parent->right_child = FALSE;
688 parent->right = node->right;
689 parent->balance -= 1;
692 else /* node has a right child */
694 GTreeNode *tmp = g_tree_node_next (node);
695 tmp->left = node->left;
698 tree->root = node->right;
701 parent->left = node->right;
702 parent->balance += 1;
706 parent->right = node->right;
707 parent->balance -= 1;
711 else /* node has a left child */
713 if (!node->right_child)
715 GTreeNode *tmp = g_tree_node_previous (node);
716 tmp->right = node->right;
719 tree->root = node->left;
722 parent->left = node->left;
723 parent->balance += 1;
727 parent->right = node->left;
728 parent->balance -= 1;
731 else /* node has a both children (pant, pant!) */
733 GTreeNode *prev = node->left;
734 GTreeNode *next = node->right;
735 GTreeNode *nextp = node;
736 int old_idx = idx + 1;
739 /* path[idx] == parent */
740 /* find the immediately next node (and its parent) */
741 while (next->left_child)
743 path[++idx] = nextp = next;
747 path[old_idx] = next;
750 /* remove 'next' from the tree */
753 if (next->right_child)
754 nextp->left = next->right;
756 nextp->left_child = FALSE;
759 next->right_child = TRUE;
760 next->right = node->right;
765 /* set the prev to point to the right place */
766 while (prev->right_child)
770 /* prepare 'next' to replace 'node' */
771 next->left_child = TRUE;
772 next->left = node->left;
773 next->balance = node->balance;
780 parent->right = next;
784 /* restore balance */
788 GTreeNode *bparent = path[--idx];
789 g_assert (!bparent || bparent->left == balance || bparent->right == balance);
790 left_node = (bparent && balance == bparent->left);
792 if(balance->balance < -1 || balance->balance > 1)
794 balance = g_tree_node_balance (balance);
796 tree->root = balance;
798 bparent->left = balance;
800 bparent->right = balance;
803 if (balance->balance != 0 || !bparent)
807 bparent->balance += 1;
809 bparent->balance -= 1;
816 if (tree->key_destroy_func)
817 tree->key_destroy_func (node->key);
818 if (tree->value_destroy_func)
819 tree->value_destroy_func (node->value);
822 g_slice_free (GTreeNode, node);
832 * @key: the key to look up
834 * Gets the value corresponding to the given key. Since a #GTree is
835 * automatically balanced as key/value pairs are added, key lookup
836 * is O(log n) (where n is the number of key/value pairs in the tree).
838 * Return value: the value corresponding to the key, or %NULL
839 * if the key was not found.
842 g_tree_lookup (GTree *tree,
847 g_return_val_if_fail (tree != NULL, NULL);
849 node = g_tree_find_node (tree, key);
851 return node ? node->value : NULL;
855 * g_tree_lookup_extended:
857 * @lookup_key: the key to look up
858 * @orig_key: returns the original key
859 * @value: returns the value associated with the key
861 * Looks up a key in the #GTree, returning the original key and the
862 * associated value. This is useful if you need to free the memory
863 * allocated for the original key, for example before calling
866 * Return value: %TRUE if the key was found in the #GTree
869 g_tree_lookup_extended (GTree *tree,
870 gconstpointer lookup_key,
876 g_return_val_if_fail (tree != NULL, FALSE);
878 node = g_tree_find_node (tree, lookup_key);
883 *orig_key = node->key;
885 *value = node->value;
895 * @func: the function to call for each node visited.
896 * If this function returns %TRUE, the traversal is stopped.
897 * @user_data: user data to pass to the function
899 * Calls the given function for each of the key/value pairs in the #GTree.
900 * The function is passed the key and value of each pair, and the given
901 * @data parameter. The tree is traversed in sorted order.
903 * The tree may not be modified while iterating over it (you can't
904 * add/remove items). To remove all items matching a predicate, you need
905 * to add each item to a list in your #GTraverseFunc as you walk over
906 * the tree, then walk the list and remove each item.
909 g_tree_foreach (GTree *tree,
915 g_return_if_fail (tree != NULL);
920 node = g_tree_first_node (tree);
924 if ((*func) (node->key, node->value, user_data))
927 node = g_tree_node_next (node);
934 * @traverse_func: the function to call for each node visited. If this
935 * function returns %TRUE, the traversal is stopped.
936 * @traverse_type: the order in which nodes are visited, one of %G_IN_ORDER,
937 * %G_PRE_ORDER and %G_POST_ORDER
938 * @user_data: user data to pass to the function
940 * Calls the given function for each node in the #GTree.
942 * Deprecated:2.2: The order of a balanced tree is somewhat arbitrary.
943 * If you just want to visit all nodes in sorted order, use
944 * g_tree_foreach() instead. If you really need to visit nodes in
945 * a different order, consider using an
946 * <link linkend="glib-N-ary-Trees">N-ary Tree</link>.
950 * @key: a key of a #GTree node
951 * @value: the value corresponding to the key
952 * @data: user data passed to g_tree_traverse()
954 * Specifies the type of function passed to g_tree_traverse(). It is
955 * passed the key and value of each node, together with the @user_data
956 * parameter passed to g_tree_traverse(). If the function returns
957 * %TRUE, the traversal is stopped.
959 * Returns: %TRUE to stop the traversal
962 g_tree_traverse (GTree *tree,
963 GTraverseFunc traverse_func,
964 GTraverseType traverse_type,
967 g_return_if_fail (tree != NULL);
972 switch (traverse_type)
975 g_tree_node_pre_order (tree->root, traverse_func, user_data);
979 g_tree_node_in_order (tree->root, traverse_func, user_data);
983 g_tree_node_post_order (tree->root, traverse_func, user_data);
987 g_warning ("g_tree_traverse(): traverse type G_LEVEL_ORDER isn't implemented.");
995 * @search_func: a function used to search the #GTree
996 * @user_data: the data passed as the second argument to @search_func
998 * Searches a #GTree using @search_func.
1000 * The @search_func is called with a pointer to the key of a key/value
1001 * pair in the tree, and the passed in @user_data. If @search_func returns
1002 * 0 for a key/value pair, then the corresponding value is returned as
1003 * the result of g_tree_search(). If @search_func returns -1, searching
1004 * will proceed among the key/value pairs that have a smaller key; if
1005 * @search_func returns 1, searching will proceed among the key/value
1006 * pairs that have a larger key.
1008 * Return value: the value corresponding to the found key, or %NULL
1009 * if the key was not found.
1012 g_tree_search (GTree *tree,
1013 GCompareFunc search_func,
1014 gconstpointer user_data)
1016 g_return_val_if_fail (tree != NULL, NULL);
1019 return g_tree_node_search (tree->root, search_func, user_data);
1028 * Gets the height of a #GTree.
1030 * If the #GTree contains no nodes, the height is 0.
1031 * If the #GTree contains only one root node the height is 1.
1032 * If the root node has children the height is 2, etc.
1034 * Return value: the height of @tree
1037 g_tree_height (GTree *tree)
1042 g_return_val_if_fail (tree != NULL, 0);
1052 height += 1 + MAX(node->balance, 0);
1054 if (!node->left_child)
1065 * Gets the number of nodes in a #GTree.
1067 * Return value: the number of nodes in @tree
1070 g_tree_nnodes (GTree *tree)
1072 g_return_val_if_fail (tree != NULL, 0);
1074 return tree->nnodes;
1078 g_tree_node_balance (GTreeNode *node)
1080 if (node->balance < -1)
1082 if (node->left->balance > 0)
1083 node->left = g_tree_node_rotate_left (node->left);
1084 node = g_tree_node_rotate_right (node);
1086 else if (node->balance > 1)
1088 if (node->right->balance < 0)
1089 node->right = g_tree_node_rotate_right (node->right);
1090 node = g_tree_node_rotate_left (node);
1097 g_tree_find_node (GTree *tree,
1109 cmp = tree->key_compare (key, node->key, tree->key_compare_data);
1114 if (!node->left_child)
1121 if (!node->right_child)
1130 g_tree_node_pre_order (GTreeNode *node,
1131 GTraverseFunc traverse_func,
1134 if ((*traverse_func) (node->key, node->value, data))
1137 if (node->left_child)
1139 if (g_tree_node_pre_order (node->left, traverse_func, data))
1143 if (node->right_child)
1145 if (g_tree_node_pre_order (node->right, traverse_func, data))
1153 g_tree_node_in_order (GTreeNode *node,
1154 GTraverseFunc traverse_func,
1157 if (node->left_child)
1159 if (g_tree_node_in_order (node->left, traverse_func, data))
1163 if ((*traverse_func) (node->key, node->value, data))
1166 if (node->right_child)
1168 if (g_tree_node_in_order (node->right, traverse_func, data))
1176 g_tree_node_post_order (GTreeNode *node,
1177 GTraverseFunc traverse_func,
1180 if (node->left_child)
1182 if (g_tree_node_post_order (node->left, traverse_func, data))
1186 if (node->right_child)
1188 if (g_tree_node_post_order (node->right, traverse_func, data))
1192 if ((*traverse_func) (node->key, node->value, data))
1199 g_tree_node_search (GTreeNode *node,
1200 GCompareFunc search_func,
1210 dir = (* search_func) (node->key, data);
1215 if (!node->left_child)
1222 if (!node->right_child)
1231 g_tree_node_rotate_left (GTreeNode *node)
1237 right = node->right;
1239 if (right->left_child)
1240 node->right = right->left;
1243 node->right_child = FALSE;
1244 right->left_child = TRUE;
1248 a_bal = node->balance;
1249 b_bal = right->balance;
1254 right->balance = b_bal - 1;
1256 right->balance = a_bal + b_bal - 2;
1257 node->balance = a_bal - 1;
1262 right->balance = a_bal - 2;
1264 right->balance = b_bal - 1;
1265 node->balance = a_bal - b_bal - 1;
1272 g_tree_node_rotate_right (GTreeNode *node)
1280 if (left->right_child)
1281 node->left = left->right;
1284 node->left_child = FALSE;
1285 left->right_child = TRUE;
1289 a_bal = node->balance;
1290 b_bal = left->balance;
1295 left->balance = b_bal + 1;
1297 left->balance = a_bal + 2;
1298 node->balance = a_bal - b_bal + 1;
1303 left->balance = b_bal + 1;
1305 left->balance = a_bal + b_bal + 2;
1306 node->balance = a_bal + 1;
1314 g_tree_node_height (GTreeNode *node)
1324 if (node->left_child)
1325 left_height = g_tree_node_height (node->left);
1327 if (node->right_child)
1328 right_height = g_tree_node_height (node->right);
1330 return MAX (left_height, right_height) + 1;
1337 g_tree_node_check (GTreeNode *node)
1346 if (node->left_child)
1348 tmp = g_tree_node_previous (node);
1349 g_assert (tmp->right == node);
1352 if (node->right_child)
1354 tmp = g_tree_node_next (node);
1355 g_assert (tmp->left == node);
1361 if (node->left_child)
1362 left_height = g_tree_node_height (node->left);
1363 if (node->right_child)
1364 right_height = g_tree_node_height (node->right);
1366 balance = right_height - left_height;
1367 g_assert (balance == node->balance);
1369 if (node->left_child)
1370 g_tree_node_check (node->left);
1371 if (node->right_child)
1372 g_tree_node_check (node->right);
1377 g_tree_node_dump (GTreeNode *node,
1380 g_print ("%*s%c\n", indent, "", *(char *)node->key);
1382 if (node->left_child)
1383 g_tree_node_dump (node->left, indent + 2);
1384 else if (node->left)
1385 g_print ("%*s<%c\n", indent + 2, "", *(char *)node->left->key);
1387 if (node->right_child)
1388 g_tree_node_dump (node->right, indent + 2);
1389 else if (node->right)
1390 g_print ("%*s>%c\n", indent + 2, "", *(char *)node->right->key);
1395 g_tree_dump (GTree *tree)
1398 g_tree_node_dump (tree->root, 0);