Binary Tree Re-balancing

Edward E. Andrews andrews at hpcupt1.HP.COM
Tue Apr 10 02:35:35 AEST 1990


Here is a translation of Wirth's PASCAL version:

-------------------------------------------------------------------------------

#include <stdio.h>
#include <stdlib.h>

#define TRUE	1
#define FALSE	0

struct node {
   int key;
   int count;
   struct node *left;
   struct node *right;
   int bal;
};

int search(int x, struct node **p)
{
   struct node *p1, *p2;
   int h;

   if (*p == NULL) {
      *p          = (struct node *) malloc(sizeof (struct node));
      (*p)->key   = x;
      (*p)->count = 1;
      (*p)->left  = NULL;
      (*p)->right = NULL;
      (*p)->bal   = 0;
      return(TRUE);
   };
   if (x == (*p)->key) {
      (*p)->count++;
      return(FALSE);
   };
   if (x < (*p)->key) {
      if ((h=search(x, &((*p)->left))) == TRUE)
	 switch ((*p)->bal) {
	    case 1:  (*p)->bal = 0;
		     return(FALSE);
	    case 0:  (*p)->bal = -1;
		     return(h);
	    case -1: p1 = (*p)->left;
		     if (p1->bal == -1) {
			(*p)->left = p1->right;
			p1->right  = *p;
			(*p)->bal  = 0;
			*p         = p1;
		     } else {
			p2         = p1->right;
			p1->right  = p2->left;
			p2->left   = p1;
			(*p)->left = p2->right;
			p2->right  = *p;
			(*p)->bal  = (p2->bal == -1?  1 : 0);
			p1->bal    = (p2->bal ==  1? -1 : 0);
			*p         = p2;
		     }
		     (*p)->bal = 0;
		     return(FALSE);
	 };
   } else {
      if ( (h=search(x, &((*p)->right))) == TRUE)
	 switch ((*p)->bal) {
	    case -1: (*p)->bal = 0;
		     return(FALSE);
	    case 0:  (*p)->bal = 1;
		     return(h);
	    case 1:  p1 = (*p)->right;
		     if (p1->bal == 1) {
			(*p)->right = p1->left;
			p1->left    = *p;
			(*p)->bal   = 0;
			*p          = p1;
		     } else {
			p2          = p1->left;
			p1->left    = p2->right;
			p2->right   = p1;
			(*p)->right = p2->left;
			p2->left    = *p;
			(*p)->bal   = (p2->bal ==  1? -1 : 0);
			p1->bal     = (p2->bal == -1?  1 : 0);
			*p          = p2;
		     }
		     (*p)->bal = 0;
		     return(FALSE);
	 }
   }
}

void visit(struct node *p)
{
   if (p != NULL) {
      printf("%d(%d)", p->key, p->bal);
      if (p->left != NULL)
	 printf("\tl:%d", p->left->key);
      if (p->right != NULL)
	 printf("\tr:%d", p->right->key);
      printf("\n");
      visit(p->left);
      visit(p->right);
   }
}

main()
{
   int i, j;
   struct node *root;
   root = (struct node *) NULL;
   for (i = 0; i < 20; i++) {
      j = random(100);
      printf("-----%d-----\n", j);
      search(j, &root);
      visit(root);
   }
}



More information about the Comp.lang.c mailing list