二叉排序树 c

来源:互联网 发布:千人基因组数据库 编辑:程序博客网 时间:2024/05/21 08:51
/* ds.h *//* Some pre define */#ifndef _HS_H#define _HS_H#include <string.h>#include <ctype.h>#include <sys/malloc.h>#include <stdio.h>#include <stdlib.h>/* State code */#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define INFEASIBLE -1#define OVERFLOW 0typedef int Status;typedef int Boolean;#endif
// bst.c#include "ds.h"#include <stdio.h>typedef int KeyType;typedef struct BiTNode{  KeyType key;  struct BiTNode *lchild, *rchild;}BiTNode, *BiTree;// Initial a bstStatus InitBST(BiTree *T){  *T = NULL;  return OK;}// search bst, if successed, p points to the node, return 1// else, return 0Status SearchBST(BiTree T, KeyType key, BiTree f, BiTree *p){  /*  *p = f, result in bus error: 10??  */  if(!T){*p = f; return FALSE;}  else if(key < T->key)return SearchBST(T->lchild, key, T, p);  else if(key > T->key)return SearchBST(T->rchild, key, T, p);  else{    *p = T;    return TRUE;  }}// Insert bst, if key exists, return False,// else, insert it and return trueStatus InsertBST(BiTree *T, KeyType key){  BiTree p;  // InitBST(p);  if(!SearchBST(*T, key, NULL, &p)){    BiTree s;    s = (BiTree)malloc(sizeof(BiTNode));    s->key = key;    s->lchild = s->rchild = NULL;    if(!p){      *T = s;    } // T == NULL    else if(key < p->key)p->lchild = s;    else{      p->rchild = s;    }    return TRUE;  }else{    return FALSE;  }}// Print bstvoid printBiTree(BiTree T, int depth){  if(T){    printf("%d", T->key);    if(T->lchild){      printf("\n");      printf("%*.s-", depth+1, "");      printBiTree(T->lchild, depth+1);    }    if(T->rchild){      printf("\n");      printf("%*.s+", depth+1, "");      printBiTree(T->rchild, depth+1);    }  }else{    return;  }}Status Delete(BiTree *T){  // empty rchild, just connect its lchild  if(!(*T)->rchild){    BiTree q;    q = (*T);    (*T) = (*T)->lchild;    free(q);  }else if(!(*T)->lchild){    BiTree q;    q = (*T);    (*T) = (*T)->rchild;    free(q);  }else{    // find the second biggest node    BiTree q;    q = (*T);    BiTree s;    s = (*T)->lchild;    while(s->rchild){      q = s;      s = s->rchild;    }    (*T)->key = s->key;    if(q != (*T))q->rchild = s->lchild;    else{      q->lchild = s->lchild;    }    free(s);  }  return TRUE;}// delete keyStatus DeleteBST(BiTree *T, KeyType key){  if(!T)return FALSE;  else{    if(key == (*T)->key)      return Delete(T);    else if(key < (*T)->key)      return DeleteBST(&(*T)->lchild, key);    else{      return DeleteBST(&(*T)->rchild, key);    }  }}int main(){  BiTree T;  InitBST(&T);  int a[7] = {45, 24, 53, 12, 90, 20, 60};  for(int i=0; i<7; i++){    InsertBST(&T, a[i]);  }  printBiTree(T, 1);  printf("\n");  DeleteBST(&T, 24);  printBiTree(T, 1);  printf("\n");}
./a.out 45  -24   -12    +20  +53   +90    -6045  -12   +20  +53   +90    -60