gtree.c 29.7 KB
Newer Older
Owen Taylor's avatar
Owen Taylor committed
1 2 3 4
/* GLIB - Library of useful routines for C programming
 * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Lesser General Public
Owen Taylor's avatar
Owen Taylor committed
6 7 8 9 10 11
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12
 * Lesser General Public License for more details.
Owen Taylor's avatar
Owen Taylor committed
13
 *
14
 * You should have received a copy of the GNU Lesser General Public
Owen Taylor's avatar
Owen Taylor committed
15 16 17 18
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
19

20
/*
21
 * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22 23 24 25 26
 * file for a list of people on the GLib Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GLib at ftp://ftp.gtk.org/pub/gtk/. 
 */

27 28 29 30
/* 
 * MT safe
 */

31
#include "config.h"
32

Owen Taylor's avatar
Owen Taylor committed
33
#include "glib.h"
34
#include "galias.h"
Owen Taylor's avatar
Owen Taylor committed
35

36 37 38
#undef G_TREE_DEBUG

#define MAX_GTREE_HEIGHT 40
Owen Taylor's avatar
Owen Taylor committed
39 40 41

typedef struct _GTreeNode  GTreeNode;

42
struct _GTree
Owen Taylor's avatar
Owen Taylor committed
43
{
44 45 46 47 48 49
  GTreeNode        *root;
  GCompareDataFunc  key_compare;
  GDestroyNotify    key_destroy_func;
  GDestroyNotify    value_destroy_func;
  gpointer          key_compare_data;
  guint             nnodes;
Owen Taylor's avatar
Owen Taylor committed
50 51 52 53
};

struct _GTreeNode
{
54 55 56 57 58 59 60
  gpointer   key;         /* key for this node */
  gpointer   value;       /* value stored at this node */
  GTreeNode *left;        /* left subtree */
  GTreeNode *right;       /* right subtree */
  gint8      balance;     /* height (left) - height (right) */
  guint8     left_child;  
  guint8     right_child;
Owen Taylor's avatar
Owen Taylor committed
61 62 63
};


64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
static GTreeNode* g_tree_node_new                   (gpointer       key,
						     gpointer       value);
static void       g_tree_insert_internal            (GTree         *tree,
						     gpointer       key,
						     gpointer       value,
						     gboolean       replace);
static gboolean   g_tree_remove_internal            (GTree         *tree,
						     gconstpointer  key,
						     gboolean       steal);
static GTreeNode* g_tree_node_balance               (GTreeNode     *node);
static GTreeNode *g_tree_find_node                  (GTree         *tree,
						     gconstpointer  key);
static gint       g_tree_node_pre_order             (GTreeNode     *node,
						     GTraverseFunc  traverse_func,
						     gpointer       data);
static gint       g_tree_node_in_order              (GTreeNode     *node,
						     GTraverseFunc  traverse_func,
						     gpointer       data);
static gint       g_tree_node_post_order            (GTreeNode     *node,
						     GTraverseFunc  traverse_func,
						     gpointer       data);
static gpointer   g_tree_node_search                (GTreeNode     *node,
						     GCompareFunc   search_func,
						     gconstpointer  data);
static GTreeNode* g_tree_node_rotate_left           (GTreeNode     *node);
static GTreeNode* g_tree_node_rotate_right          (GTreeNode     *node);
#ifdef G_TREE_DEBUG
static void       g_tree_node_check                 (GTreeNode     *node);
#endif
Owen Taylor's avatar
Owen Taylor committed
93 94


95 96 97 98
static GTreeNode*
g_tree_node_new (gpointer key,
		 gpointer value)
{
99
  GTreeNode *node = g_slice_new (GTreeNode);
100 101 102 103

  node->balance = 0;
  node->left = NULL;
  node->right = NULL;
104 105
  node->left_child = FALSE;
  node->right_child = FALSE;
106 107 108 109 110 111
  node->key = key;
  node->value = value;

  return node;
}

112 113 114
/**
 * g_tree_new:
 * @key_compare_func: the function used to order the nodes in the #GTree.
115
 *   It should return values similar to the standard strcmp() function -
116 117 118 119 120 121 122 123 124 125
 *   0 if the two arguments are equal, a negative value if the first argument 
 *   comes before the second, or a positive value if the first argument comes 
 *   after the second.
 * 
 * Creates a new #GTree.
 * 
 * Return value: a new #GTree.
 **/
GTree*
g_tree_new (GCompareFunc key_compare_func)
Owen Taylor's avatar
Owen Taylor committed
126
{
127 128
  g_return_val_if_fail (key_compare_func != NULL, NULL);

129 130
  return g_tree_new_full ((GCompareDataFunc) key_compare_func, NULL,
                          NULL, NULL);
Owen Taylor's avatar
Owen Taylor committed
131 132
}

133 134
/**
 * g_tree_new_with_data:
135
 * @key_compare_func: qsort()-style comparison function.
136 137 138 139 140 141 142
 * @key_compare_data: data to pass to comparison function.
 * 
 * Creates a new #GTree with a comparison function that accepts user data.
 * See g_tree_new() for more details.
 * 
 * Return value: a new #GTree.
 **/
143
GTree*
144 145
g_tree_new_with_data (GCompareDataFunc key_compare_func,
 		      gpointer         key_compare_data)
146
{
147 148 149 150
  g_return_val_if_fail (key_compare_func != NULL, NULL);
  
  return g_tree_new_full (key_compare_func, key_compare_data, 
 			  NULL, NULL);
151 152
}

153 154
/**
 * g_tree_new_full:
155
 * @key_compare_func: qsort()-style comparison function.
156 157
 * @key_compare_data: data to pass to comparison function.
 * @key_destroy_func: a function to free the memory allocated for the key 
Matthias Clasen's avatar
Matthias Clasen committed
158
 *   used when removing the entry from the #GTree or %NULL if you don't
159 160
 *   want to supply such a function.
 * @value_destroy_func: a function to free the memory allocated for the 
Matthias Clasen's avatar
Matthias Clasen committed
161
 *   value used when removing the entry from the #GTree or %NULL if you 
162 163 164 165 166 167 168 169 170 171 172 173 174 175
 *   don't want to supply such a function.
 * 
 * Creates a new #GTree like g_tree_new() and allows to specify functions 
 * to free the memory allocated for the key and value that get called when 
 * removing the entry from the #GTree.
 * 
 * Return value: a new #GTree.
 **/
GTree*	 
g_tree_new_full (GCompareDataFunc key_compare_func,
 		 gpointer         key_compare_data, 		 
                 GDestroyNotify   key_destroy_func,
 		 GDestroyNotify   value_destroy_func)
{
176
  GTree *tree;
177 178 179
  
  g_return_val_if_fail (key_compare_func != NULL, NULL);
  
180 181 182 183 184 185
  tree = g_new (GTree, 1);
  tree->root               = NULL;
  tree->key_compare        = key_compare_func;
  tree->key_destroy_func   = key_destroy_func;
  tree->value_destroy_func = value_destroy_func;
  tree->key_compare_data   = key_compare_data;
186
  tree->nnodes             = 0;
187
  
188
  return tree;
189
}
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
static inline GTreeNode *
g_tree_first_node (GTree *tree)
{
  GTreeNode *tmp;

  if (!tree->root)
    return NULL;

  tmp = tree->root;

  while (tmp->left_child)
    tmp = tmp->left;

  return tmp;
} 

static inline GTreeNode *
g_tree_node_previous (GTreeNode *node)
{
  GTreeNode *tmp;

  tmp = node->left;

  if (node->left_child)
    while (tmp->right_child)
      tmp = tmp->right;

  return tmp;
}
		  
static inline GTreeNode *
g_tree_node_next (GTreeNode *node)
{
  GTreeNode *tmp;

  tmp = node->right;

  if (node->right_child)
    while (tmp->left_child)
      tmp = tmp->left;

  return tmp;
}
		  
235 236 237 238 239 240 241 242 243
/**
 * g_tree_destroy:
 * @tree: a #GTree.
 * 
 * Destroys the #GTree. If keys and/or values are dynamically allocated, you 
 * should either free them first or create the #GTree using g_tree_new_full().
 * In the latter case the destroy functions you supplied will be called on 
 * all keys and values before destroying the #GTree.
 **/
Owen Taylor's avatar
Owen Taylor committed
244 245 246
void
g_tree_destroy (GTree *tree)
{
247 248 249
  GTreeNode *node;
  GTreeNode *next;

Owen Taylor's avatar
Owen Taylor committed
250 251
  g_return_if_fail (tree != NULL);

252 253 254 255 256 257 258 259 260 261 262 263 264 265
  node = g_tree_first_node (tree);
  
  while (node)
    {
      next = g_tree_node_next (node);

      if (tree->key_destroy_func)
	tree->key_destroy_func (node->key);
      if (tree->value_destroy_func)
	tree->value_destroy_func (node->value);
      g_slice_free (GTreeNode, node);

      node = next;
    }
266

267
  g_free (tree);
Owen Taylor's avatar
Owen Taylor committed
268 269
}

270 271
/**
 * g_tree_insert:
272
 * @tree: a #GTree.
273 274 275 276
 * @key: the key to insert.
 * @value: the value corresponding to the key.
 * 
 * Inserts a key/value pair into a #GTree. If the given key already exists 
277 278
 * in the #GTree its corresponding value is set to the new value. If you 
 * supplied a value_destroy_func when creating the #GTree, the old value is 
Matthias Clasen's avatar
Matthias Clasen committed
279
 * freed using that function. If you supplied a @key_destroy_func when 
280
 * creating the #GTree, the passed key is freed using that function.
281 282 283 284
 *
 * The tree is automatically 'balanced' as new key/value pairs are added,
 * so that the distance from the root to every leaf is as small as possible.
 **/
Owen Taylor's avatar
Owen Taylor committed
285 286 287 288 289
void
g_tree_insert (GTree    *tree,
	       gpointer  key,
	       gpointer  value)
{
290 291
  g_return_if_fail (tree != NULL);

292 293 294 295 296
  g_tree_insert_internal (tree, key, value, FALSE);

#ifdef G_TREE_DEBUG
  g_tree_node_check (tree->root);
#endif
297 298 299 300
}

/**
 * g_tree_replace:
301
 * @tree: a #GTree.
302 303 304 305 306
 * @key: the key to insert.
 * @value: the value corresponding to the key.
 * 
 * Inserts a new key and value into a #GTree similar to g_tree_insert(). 
 * The difference is that if the key already exists in the #GTree, it gets 
Matthias Clasen's avatar
Matthias Clasen committed
307
 * replaced by the new key. If you supplied a @value_destroy_func when 
308
 * creating the #GTree, the old value is freed using that function. If you 
Matthias Clasen's avatar
Matthias Clasen committed
309
 * supplied a @key_destroy_func when creating the #GTree, the old key is 
310 311 312 313 314 315 316 317 318 319
 * freed using that function. 
 *
 * The tree is automatically 'balanced' as new key/value pairs are added,
 * so that the distance from the root to every leaf is as small as possible.
 **/
void
g_tree_replace (GTree    *tree,
		gpointer  key,
		gpointer  value)
{
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
  g_return_if_fail (tree != NULL);

  g_tree_insert_internal (tree, key, value, TRUE);

#ifdef G_TREE_DEBUG
  g_tree_node_check (tree->root);
#endif
}

/* internal insert routine */
static void
g_tree_insert_internal (GTree    *tree,
                        gpointer  key,
                        gpointer  value,
                        gboolean  replace)
{
  GTreeNode *node;
  GTreeNode *path[MAX_GTREE_HEIGHT];
  int idx;
Owen Taylor's avatar
Owen Taylor committed
339 340 341

  g_return_if_fail (tree != NULL);

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  if (!tree->root)
    {
      tree->root = g_tree_node_new (key, value);
      tree->nnodes++;
      return;
    }

  idx = 0;
  path[idx++] = NULL;
  node = tree->root;

  while (1)
    {
      int cmp = tree->key_compare (key, node->key, tree->key_compare_data);
      
      if (cmp == 0)
        {
          if (tree->value_destroy_func)
            tree->value_destroy_func (node->value);

          node->value = value;

          if (replace)
            {
              if (tree->key_destroy_func)
                tree->key_destroy_func (node->key);

              node->key = key;
            }
          else
            {
              /* free the passed key */
              if (tree->key_destroy_func)
                tree->key_destroy_func (key);
            }

          return;
        }
      else if (cmp < 0)
        {
          if (node->left_child)
            {
              path[idx++] = node;
              node = node->left;
            }
          else
            {
              GTreeNode *child = g_tree_node_new (key, value);

              child->left = node->left;
              child->right = node;
              node->left = child;
              node->left_child = TRUE;
              node->balance -= 1;

	      tree->nnodes++;

              break;
            }
        }
      else
        {
          if (node->right_child)
            {
              path[idx++] = node;
              node = node->right;
            }
          else
            {
              GTreeNode *child = g_tree_node_new (key, value);

              child->right = node->right;
              child->left = node;
              node->right = child;
              node->right_child = TRUE;
              node->balance += 1;

	      tree->nnodes++;

              break;
            }
        }
    }

  /* restore balance. This is the goodness of a non-recursive
     implementation, when we are done with balancing we 'break'
     the loop and we are done. */
  while (1)
    {
      GTreeNode *bparent = path[--idx];
      gboolean left_node = (bparent && node == bparent->left);
      g_assert (!bparent || bparent->left == node || bparent->right == node);

      if (node->balance < -1 || node->balance > 1)
        {
          node = g_tree_node_balance (node);
          if (bparent == NULL)
            tree->root = node;
          else if (left_node)
            bparent->left = node;
          else
            bparent->right = node;
        }

      if (node->balance == 0 || bparent == NULL)
        break;
      
      if (left_node)
        bparent->balance -= 1;
      else
        bparent->balance += 1;

      node = bparent;
    }
Owen Taylor's avatar
Owen Taylor committed
456 457
}

458 459
/**
 * g_tree_remove:
460
 * @tree: a #GTree.
461 462 463 464 465
 * @key: the key to remove.
 * 
 * Removes a key/value pair from a #GTree.
 *
 * If the #GTree was created using g_tree_new_full(), the key and value 
Matthias Clasen's avatar
Matthias Clasen committed
466
 * are freed using the supplied destroy functions, otherwise you have to 
467
 * make sure that any dynamically allocated values are freed yourself.
468
 * If the key does not exist in the #GTree, the function does nothing.
469
 *
Matthias Clasen's avatar
Matthias Clasen committed
470 471
 * Returns: %TRUE if the key was found (prior to 2.8, this function returned 
 *   nothing)
472
 **/
473
gboolean
474 475
g_tree_remove (GTree         *tree,
	       gconstpointer  key)
Owen Taylor's avatar
Owen Taylor committed
476
{
477
  gboolean removed;
Owen Taylor's avatar
Owen Taylor committed
478

479 480
  g_return_val_if_fail (tree != NULL, FALSE);

481 482 483 484 485
  removed = g_tree_remove_internal (tree, key, FALSE);

#ifdef G_TREE_DEBUG
  g_tree_node_check (tree->root);
#endif
486 487

  return removed;
488 489 490 491
}

/**
 * g_tree_steal:
492
 * @tree: a #GTree.
493 494 495 496
 * @key: the key to remove.
 * 
 * Removes a key and its associated value from a #GTree without calling 
 * the key and value destroy functions.
497 498
 *
 * If the key does not exist in the #GTree, the function does nothing.
499
 *
Matthias Clasen's avatar
Matthias Clasen committed
500 501
 * Returns: %TRUE if the key was found (prior to 2.8, this function returned 
 *    nothing)
502
 **/
503
gboolean
504 505 506
g_tree_steal (GTree         *tree,
              gconstpointer  key)
{
507 508 509 510
  gboolean removed;

  g_return_val_if_fail (tree != NULL, FALSE);

511 512 513 514 515
  removed = g_tree_remove_internal (tree, key, TRUE);

#ifdef G_TREE_DEBUG
  g_tree_node_check (tree->root);
#endif
516

517
  return removed;
Owen Taylor's avatar
Owen Taylor committed
518 519
}

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
/* internal remove routine */
static gboolean
g_tree_remove_internal (GTree         *tree,
                        gconstpointer  key,
                        gboolean       steal)
{
  GTreeNode *node, *parent, *balance;
  GTreeNode *path[MAX_GTREE_HEIGHT];
  int idx;
  gboolean left_node;

  g_return_val_if_fail (tree != NULL, FALSE);

  if (!tree->root)
    return FALSE;

  idx = 0;
  path[idx++] = NULL;
  node = tree->root;

  while (1)
    {
      int cmp = tree->key_compare (key, node->key, tree->key_compare_data);
      
      if (cmp == 0)
        break;
      else if (cmp < 0)
        {
          if (!node->left_child)
            return FALSE;
	  
	  path[idx++] = node;
	  node = node->left;
        }
      else
        {
          if (!node->right_child)
            return FALSE;
	  
	  path[idx++] = node;
	  node = node->right;
        }
    }

  /* the following code is almost equal to g_tree_remove_node,
     except that we do not have to call g_tree_node_parent. */
  balance = parent = path[--idx];
  g_assert (!parent || parent->left == node || parent->right == node);
  left_node = (parent && node == parent->left);

  if (!node->left_child)
    {
      if (!node->right_child)
        {
          if (!parent)
            tree->root = NULL;
          else if (left_node)
            {
              parent->left_child = FALSE;
              parent->left = node->left;
              parent->balance += 1;
            }
          else
            {
              parent->right_child = FALSE;
              parent->right = node->right;
              parent->balance -= 1;
            }
        }
      else /* node has a right child */
        {
          GTreeNode *tmp = g_tree_node_next (node);
	  tmp->left = node->left;

          if (!parent)
            tree->root = node->right;
          else if (left_node)
            {
              parent->left = node->right;
              parent->balance += 1;
            }
          else
            {
              parent->right = node->right;
              parent->balance -= 1;
            }
        }
    }
  else /* node has a left child */
    {
      if (!node->right_child)
        {
          GTreeNode *tmp = g_tree_node_previous (node);
          tmp->right = node->right;
	  
          if (parent == NULL)
            tree->root = node->left;
          else if (left_node)
            {
              parent->left = node->left;
              parent->balance += 1;
            }
          else
            {
              parent->right = node->left;
              parent->balance -= 1;
            }
        }
      else /* node has a both children (pant, pant!) */
        {
	  GTreeNode *prev = node->left;
	  GTreeNode *next = node->right;
	  GTreeNode *nextp = node;
	  int old_idx = idx + 1;
	  idx++;
	  
	  /* path[idx] == parent */
	  /* find the immediately next node (and its parent) */
	  while (next->left_child)
            {
	      path[++idx] = nextp = next;
	      next = next->left;
            }
 	  
	  path[old_idx] = next;
	  balance = path[idx];
	  
	  /* remove 'next' from the tree */
	  if (nextp != node)
	    {
	      if (next->right_child)
		nextp->left = next->right;
	      else
		nextp->left_child = FALSE;
	      nextp->balance += 1;
	      
	      next->right_child = TRUE;
	      next->right = node->right;
	    }
	  else
	    node->balance -= 1;
	    
	  /* set the prev to point to the right place */
	  while (prev->right_child)
	    prev = prev->right;
	  prev->right = next;
	    
	  /* prepare 'next' to replace 'node' */
	  next->left_child = TRUE;
	  next->left = node->left;
	  next->balance = node->balance;
	  
	  if (!parent)
	    tree->root = next;
	  else if (left_node)
	    parent->left = next;
	  else
	    parent->right = next;
        }
    }
  
  /* restore balance */
  if (balance)
    while (1)
      {
	GTreeNode *bparent = path[--idx];
	g_assert (!bparent || bparent->left == balance || bparent->right == balance);
	left_node = (bparent && balance == bparent->left);
			      
	if(balance->balance < -1 || balance->balance > 1)
	  {
	    balance = g_tree_node_balance (balance);
	    if (!bparent)
	      tree->root = balance;
	    else if (left_node)
	      bparent->left = balance;
	    else
	      bparent->right = balance;
	  }
	
	if (balance->balance != 0 || !bparent)
	  break;
	
	if (left_node)
	  bparent->balance += 1;
	else
	  bparent->balance -= 1;
	
	balance = bparent;
      }
  
  if (!steal)
    {
      if (tree->key_destroy_func)
        tree->key_destroy_func (node->key);
      if (tree->value_destroy_func)
        tree->value_destroy_func (node->value);
    }

  g_slice_free (GTreeNode, node);

  tree->nnodes--;

  return TRUE;
}

726 727 728 729 730 731 732 733 734
/**
 * g_tree_lookup:
 * @tree: a #GTree.
 * @key: the key to look up.
 * 
 * Gets the value corresponding to the given key. Since a #GTree is 
 * automatically balanced as key/value pairs are added, key lookup is very 
 * fast.
 *
735 736
 * Return value: the value corresponding to the key, or %NULL if the key was
 * not found.
737
 **/
Owen Taylor's avatar
Owen Taylor committed
738
gpointer
739 740
g_tree_lookup (GTree         *tree,
	       gconstpointer  key)
Owen Taylor's avatar
Owen Taylor committed
741
{
742
  GTreeNode *node;
Owen Taylor's avatar
Owen Taylor committed
743 744 745

  g_return_val_if_fail (tree != NULL, NULL);

746 747
  node = g_tree_find_node (tree, key);
  
748
  return node ? node->value : NULL;
Owen Taylor's avatar
Owen Taylor committed
749 750
}

751 752 753 754 755 756 757 758
/**
 * g_tree_lookup_extended:
 * @tree: a #GTree.
 * @lookup_key: the key to look up.
 * @orig_key: returns the original key.
 * @value: returns the value associated with the key.
 * 
 * Looks up a key in the #GTree, returning the original key and the
Matthias Clasen's avatar
Matthias Clasen committed
759
 * associated value and a #gboolean which is %TRUE if the key was found. This 
760 761 762
 * is useful if you need to free the memory allocated for the original key, 
 * for example before calling g_tree_remove().
 * 
Matthias Clasen's avatar
Matthias Clasen committed
763
 * Return value: %TRUE if the key was found in the #GTree.
764
 **/
765 766 767 768 769 770 771 772 773 774
gboolean
g_tree_lookup_extended (GTree         *tree,
                        gconstpointer  lookup_key,
                        gpointer      *orig_key,
                        gpointer      *value)
{
  GTreeNode *node;
  
  g_return_val_if_fail (tree != NULL, FALSE);
  
775 776
  node = g_tree_find_node (tree, lookup_key);
  
777 778 779 780 781 782 783 784 785 786 787 788
  if (node)
    {
      if (orig_key)
        *orig_key = node->key;
      if (value)
        *value = node->value;
      return TRUE;
    }
  else
    return FALSE;
}

789 790 791 792
/**
 * g_tree_foreach:
 * @tree: a #GTree.
 * @func: the function to call for each node visited. If this function
Matthias Clasen's avatar
Matthias Clasen committed
793
 *   returns %TRUE, the traversal is stopped.
794 795 796 797
 * @user_data: user data to pass to the function.
 * 
 * Calls the given function for each of the key/value pairs in the #GTree.
 * The function is passed the key and value of each pair, and the given
798 799 800 801 802 803
 * @data parameter. The tree is traversed in sorted order.
 *
 * The tree may not be modified while iterating over it (you can't 
 * add/remove items). To remove all items matching a predicate, you need 
 * to add each item to a list in your #GTraverseFunc as you walk over 
 * the tree, then walk the list and remove each item.
804 805 806 807 808 809
 **/
void
g_tree_foreach (GTree         *tree,
                GTraverseFunc  func,
                gpointer       user_data)
{
810 811
  GTreeNode *node;

812 813
  g_return_if_fail (tree != NULL);
  
814
  if (!tree->root)
815 816
    return;

817 818 819 820 821 822 823 824 825
  node = g_tree_first_node (tree);
  
  while (node)
    {
      if ((*func) (node->key, node->value, user_data))
	break;
      
      node = g_tree_node_next (node);
    }
826 827 828 829 830 831
}

/**
 * g_tree_traverse:
 * @tree: a #GTree.
 * @traverse_func: the function to call for each node visited. If this 
Matthias Clasen's avatar
Matthias Clasen committed
832
 *   function returns %TRUE, the traversal is stopped.
833 834 835 836
 * @traverse_type: the order in which nodes are visited, one of %G_IN_ORDER,
 *   %G_PRE_ORDER and %G_POST_ORDER.
 * @user_data: user data to pass to the function.
 * 
837 838
 * Calls the given function for each node in the #GTree. 
 *
839
 * Deprecated:2.2: The order of a balanced tree is somewhat arbitrary. If you 
840
 * just want to visit all nodes in sorted order, use g_tree_foreach() 
841
 * instead. If you really need to visit nodes in a different order, consider
842
 * using an <link linkend="glib-N-ary-Trees">N-ary Tree</link>.
843
 **/
Owen Taylor's avatar
Owen Taylor committed
844 845 846 847
void
g_tree_traverse (GTree         *tree,
		 GTraverseFunc  traverse_func,
		 GTraverseType  traverse_type,
848
		 gpointer       user_data)
Owen Taylor's avatar
Owen Taylor committed
849 850 851
{
  g_return_if_fail (tree != NULL);

852
  if (!tree->root)
853
    return;
Owen Taylor's avatar
Owen Taylor committed
854 855 856 857

  switch (traverse_type)
    {
    case G_PRE_ORDER:
858
      g_tree_node_pre_order (tree->root, traverse_func, user_data);
Owen Taylor's avatar
Owen Taylor committed
859 860 861
      break;

    case G_IN_ORDER:
862
      g_tree_node_in_order (tree->root, traverse_func, user_data);
Owen Taylor's avatar
Owen Taylor committed
863 864 865
      break;

    case G_POST_ORDER:
866
      g_tree_node_post_order (tree->root, traverse_func, user_data);
Owen Taylor's avatar
Owen Taylor committed
867
      break;
Tim Janik's avatar
Tim Janik committed
868 869 870 871
    
    case G_LEVEL_ORDER:
      g_warning ("g_tree_traverse(): traverse type G_LEVEL_ORDER isn't implemented.");
      break;
Owen Taylor's avatar
Owen Taylor committed
872 873 874
    }
}

875 876 877
/**
 * g_tree_search:
 * @tree: a #GTree.
878
 * @search_func: a function used to search the #GTree. 
879 880 881
 * @user_data: the data passed as the second argument to the @search_func 
 * function.
 * 
882
 * Searches a #GTree using @search_func.
883
 *
Matthias Clasen's avatar
Matthias Clasen committed
884 885 886 887 888 889
 * The @search_func is called with a pointer to the key of a key/value pair in 
 * the tree, and the passed in @user_data. If @search_func returns 0 for a 
 * key/value pair, then g_tree_search_func() will return the value of that 
 * pair. If @search_func returns -1,  searching will proceed among the 
 * key/value pairs that have a smaller key; if @search_func returns 1, 
 * searching will proceed among the key/value pairs that have a larger key.
890
 *
Matthias Clasen's avatar
Matthias Clasen committed
891
 * Return value: the value corresponding to the found key, or %NULL if the key 
892
 * was not found.
893
 **/
Owen Taylor's avatar
Owen Taylor committed
894
gpointer
895 896 897
g_tree_search (GTree         *tree,
	       GCompareFunc   search_func,
	       gconstpointer  user_data)
Owen Taylor's avatar
Owen Taylor committed
898 899 900
{
  g_return_val_if_fail (tree != NULL, NULL);

901 902
  if (tree->root)
    return g_tree_node_search (tree->root, search_func, user_data);
903 904
  else
    return NULL;
Owen Taylor's avatar
Owen Taylor committed
905 906
}

907 908 909 910 911 912 913 914 915 916 917 918
/**
 * g_tree_height:
 * @tree: a #GTree.
 * 
 * Gets the height of a #GTree.
 *
 * If the #GTree contains no nodes, the height is 0.
 * If the #GTree contains only one root node the height is 1.
 * If the root node has children the height is 2, etc.
 * 
 * Return value: the height of the #GTree.
 **/
Owen Taylor's avatar
Owen Taylor committed
919 920 921
gint
g_tree_height (GTree *tree)
{
922 923 924
  GTreeNode *node;
  gint height;

Owen Taylor's avatar
Owen Taylor committed
925 926
  g_return_val_if_fail (tree != NULL, 0);

927
  if (!tree->root)
928
    return 0;
929 930 931 932 933 934 935 936 937 938 939 940 941

  height = 0;
  node = tree->root;

  while (1)
    {
      height += 1 + MAX(node->balance, 0);

      if (!node->left_child)
	return height;
      
      node = node->left;
    }
Owen Taylor's avatar
Owen Taylor committed
942 943
}

944 945 946 947 948 949 950 951
/**
 * g_tree_nnodes:
 * @tree: a #GTree.
 * 
 * Gets the number of nodes in a #GTree.
 * 
 * Return value: the number of nodes in the #GTree.
 **/
Owen Taylor's avatar
Owen Taylor committed
952 953 954 955 956
gint
g_tree_nnodes (GTree *tree)
{
  g_return_val_if_fail (tree != NULL, 0);

957
  return tree->nnodes;
Owen Taylor's avatar
Owen Taylor committed
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
}

static GTreeNode*
g_tree_node_balance (GTreeNode *node)
{
  if (node->balance < -1)
    {
      if (node->left->balance > 0)
	node->left = g_tree_node_rotate_left (node->left);
      node = g_tree_node_rotate_right (node);
    }
  else if (node->balance > 1)
    {
      if (node->right->balance < 0)
	node->right = g_tree_node_rotate_right (node->right);
      node = g_tree_node_rotate_left (node);
    }

  return node;
}

979
static GTreeNode *
980 981
g_tree_find_node (GTree        *tree,
		  gconstpointer key)
Owen Taylor's avatar
Owen Taylor committed
982
{
983
  GTreeNode *node;
Owen Taylor's avatar
Owen Taylor committed
984 985
  gint cmp;

986
  node = tree->root;
Owen Taylor's avatar
Owen Taylor committed
987 988 989
  if (!node)
    return NULL;

990
  while (1)
Owen Taylor's avatar
Owen Taylor committed
991
    {
992 993 994 995 996 997 998
      cmp = tree->key_compare (key, node->key, tree->key_compare_data);
      if (cmp == 0)
	return node;
      else if (cmp < 0)
	{
	  if (!node->left_child)
	    return NULL;
Owen Taylor's avatar
Owen Taylor committed
999

1000 1001 1002 1003 1004 1005
	  node = node->left;
	}
      else
	{
	  if (!node->right_child)
	    return NULL;
Owen Taylor's avatar
Owen Taylor committed
1006

1007 1008 1009
	  node = node->right;
	}
    }
Owen Taylor's avatar
Owen Taylor committed
1010 1011 1012 1013 1014 1015 1016 1017 1018
}

static gint
g_tree_node_pre_order (GTreeNode     *node,
		       GTraverseFunc  traverse_func,
		       gpointer       data)
{
  if ((*traverse_func) (node->key, node->value, data))
    return TRUE;
1019 1020

  if (node->left_child)
Owen Taylor's avatar
Owen Taylor committed
1021 1022 1023 1024
    {
      if (g_tree_node_pre_order (node->left, traverse_func, data))
	return TRUE;
    }
1025 1026

  if (node->right_child)
Owen Taylor's avatar
Owen Taylor committed
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    {
      if (g_tree_node_pre_order (node->right, traverse_func, data))
	return TRUE;
    }

  return FALSE;
}

static gint
g_tree_node_in_order (GTreeNode     *node,
		      GTraverseFunc  traverse_func,
		      gpointer       data)
{
1040
  if (node->left_child)
Owen Taylor's avatar
Owen Taylor committed
1041 1042 1043 1044
    {
      if (g_tree_node_in_order (node->left, traverse_func, data))
	return TRUE;
    }
1045

Owen Taylor's avatar
Owen Taylor committed
1046 1047
  if ((*traverse_func) (node->key, node->value, data))
    return TRUE;
1048 1049

  if (node->right_child)
Owen Taylor's avatar
Owen Taylor committed
1050 1051 1052 1053
    {
      if (g_tree_node_in_order (node->right, traverse_func, data))
	return TRUE;
    }
1054
  
Owen Taylor's avatar
Owen Taylor committed
1055 1056 1057 1058 1059 1060 1061 1062
  return FALSE;
}

static gint
g_tree_node_post_order (GTreeNode     *node,
			GTraverseFunc  traverse_func,
			gpointer       data)
{
1063
  if (node->left_child)
Owen Taylor's avatar
Owen Taylor committed
1064 1065 1066 1067
    {
      if (g_tree_node_post_order (node->left, traverse_func, data))
	return TRUE;
    }
1068 1069

  if (node->right_child)
Owen Taylor's avatar
Owen Taylor committed
1070 1071 1072 1073
    {
      if (g_tree_node_post_order (node->right, traverse_func, data))
	return TRUE;
    }
1074

Owen Taylor's avatar
Owen Taylor committed
1075 1076 1077 1078 1079 1080 1081
  if ((*traverse_func) (node->key, node->value, data))
    return TRUE;

  return FALSE;
}

static gpointer
1082 1083 1084
g_tree_node_search (GTreeNode     *node,
		    GCompareFunc   search_func,
		    gconstpointer  data)
Owen Taylor's avatar
Owen Taylor committed
1085 1086 1087 1088 1089 1090
{
  gint dir;

  if (!node)
    return NULL;

1091
  while (1) 
Owen Taylor's avatar
Owen Taylor committed
1092
    {
1093 1094 1095 1096 1097 1098 1099
      dir = (* search_func) (node->key, data);
      if (dir == 0)
	return node->value;
      else if (dir < 0) 
	{ 
	  if (!node->left_child)
	    return NULL;
Owen Taylor's avatar
Owen Taylor committed
1100

1101 1102 1103 1104 1105 1106 1107 1108 1109
	  node = node->left;
	}
      else
	{
	  if (!node->right_child)
	    return NULL;
	  
	  node = node->right;
	}
Owen Taylor's avatar
Owen Taylor committed
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    }
}

static GTreeNode*
g_tree_node_rotate_left (GTreeNode *node)
{
  GTreeNode *right;
  gint a_bal;
  gint b_bal;

  right = node->right;

1122 1123 1124 1125 1126 1127 1128 1129
  if (right->left_child)
    node->right = right->left;
  else
    {
      node->right_child = FALSE;
      node->right = right;
      right->left_child = TRUE;
    }
Owen Taylor's avatar
Owen Taylor committed
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
  right->left = node;

  a_bal = node->balance;
  b_bal = right->balance;

  if (b_bal <= 0)
    {
      if (a_bal >= 1)
	right->balance = b_bal - 1;
      else
	right->balance = a_bal + b_bal - 2;
      node->balance = a_bal - 1;
    }
  else
    {
      if (a_bal <= b_bal)
	right->balance = a_bal - 2;
      else
	right->balance = b_bal - 1;
      node->balance = a_bal - b_bal - 1;
    }

  return right;
}

static GTreeNode*
g_tree_node_rotate_right (GTreeNode *node)
{
  GTreeNode *left;
  gint a_bal;
  gint b_bal;

  left = node->left;

1164 1165 1166 1167 1168 1169 1170 1171
  if (left->right_child)
    node->left = left->right;
  else
    {
      node->left_child = FALSE;
      node->left = left;
      left->right_child = TRUE;
    }
Owen Taylor's avatar
Owen Taylor committed
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
  left->right = node;

  a_bal = node->balance;
  b_bal = left->balance;

  if (b_bal <= 0)
    {
      if (b_bal > a_bal)
	left->balance = b_bal + 1;
      else
	left->balance = a_bal + 2;
      node->balance = a_bal - b_bal + 1;
    }
  else
    {
      if (a_bal <= -1)
	left->balance = b_bal + 1;
      else
	left->balance = a_bal + b_bal + 2;
      node->balance = a_bal + 1;
    }

  return left;
}

1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
#ifdef G_TREE_DEBUG
static gint
g_tree_node_height (GTreeNode *node)
{
  gint left_height;
  gint right_height;

  if (node)
    {
      left_height = 0;
      right_height = 0;

      if (node->left_child)
	left_height = g_tree_node_height (node->left);

      if (node->right_child)
	right_height = g_tree_node_height (node->right);

      return MAX (left_height, right_height) + 1;
    }

  return 0;
}

Owen Taylor's avatar
Owen Taylor committed
1221 1222 1223 1224 1225 1226
static void
g_tree_node_check (GTreeNode *node)
{
  gint left_height;
  gint right_height;
  gint balance;
1227 1228
  GTreeNode *tmp;

Owen Taylor's avatar
Owen Taylor committed
1229 1230
  if (node)
    {
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
      if (node->left_child)
	{
	  tmp = g_tree_node_previous (node);
	  g_assert (tmp->right == node);
	}

      if (node->right_child)
	{
	  tmp = g_tree_node_next (node);
	  g_assert (tmp->left == node);
	}

Owen Taylor's avatar
Owen Taylor committed
1243 1244
      left_height = 0;
      right_height = 0;
1245
      
1246
      if (node->left_child)
Owen Taylor's avatar
Owen Taylor committed
1247
	left_height = g_tree_node_height (node->left);
1248
      if (node->right_child)
Owen Taylor's avatar
Owen Taylor committed
1249
	right_height = g_tree_node_height (node->right);
1250
      
Owen Taylor's avatar
Owen Taylor committed
1251
      balance = right_height - left_height;
1252
      g_assert (balance == node->balance);
1253
      
1254
      if (node->left_child)
Owen Taylor's avatar
Owen Taylor committed
1255
	g_tree_node_check (node->left);
1256
      if (node->right_child)
Owen Taylor's avatar
Owen Taylor committed
1257 1258 1259
	g_tree_node_check (node->right);
    }
}
1260

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
static void
g_tree_node_dump (GTreeNode *node, 
		  gint       indent)
{
  g_print ("%*s%c\n", indent, "", *(char *)node->key);

  if (node->left_child)
    g_tree_node_dump (node->left, indent + 2);
  else if (node->left)
    g_print ("%*s<%c\n", indent + 2, "", *(char *)node->left->key);

  if (node->right_child)
    g_tree_node_dump (node->right, indent + 2);
  else if (node->right)
    g_print ("%*s>%c\n", indent + 2, "", *(char *)node->right->key);
}


void
g_tree_dump (GTree *tree)
{
  if (tree->root)
    g_tree_node_dump (tree->root, 0);
}
#endif


1288 1289
#define __G_TREE_C__
#include "galiasdef.c"
1290