Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!ucsd!ucbvax!hplabs!hpda!hpcupt1!andrews From: andrews@hpcupt1.HP.COM (Edward E. Andrews) Newsgroups: comp.lang.c Subject: Re: Binary Tree Re-balancing Message-ID: <5940030@hpcupt1.HP.COM> Date: 9 Apr 90 16:35:35 GMT References: <10403@wpi.wpi.edu> Organization: Hewlett Packard, Cupertino Lines: 117 Here is a translation of Wirth's PASCAL version: ------------------------------------------------------------------------------- #include #include #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); } }