#ifndef _HS_H
#define _HS_H
#include <string.h>
#include <ctype.h>
#include <sys/malloc.h>
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW 0
typedef int Status;
typedef int Boolean;
#endif
#include "ds.h"
#include <stdio.h>
typedef int KeyType;
typedef struct BiTNode{
KeyType key;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
Status InitBST(BiTree *T){
*T = NULL;
return OK;
}
Status SearchBST(BiTree T, KeyType key, BiTree f, BiTree *p){
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;
}
}
Status InsertBST(BiTree *T, KeyType key){
BiTree 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;
}
else if(key < p->key)p->lchild = s;
else{
p->rchild = s;
}
return TRUE;
}else{
return FALSE;
}
}
void 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){
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{
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;
}
Status 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
-60
45
-12
+20
+53
+90
-60