插入代码A:
BinTree Insert( BinTree BST, ElementType X ){
BinTree p=BST,pre=NULL;
BinTree q=(BinTree)malloc(sizeof (struct TNode));
q->Data=X;
q->Left=q->Right=NULL;
if(BST==NULL)
BST=q;
else{
while(p){
pre=p;
if(X>p->Data){
p=p->Right;
}
else if(X<p->Data){
p=p->Left;
}
}
if(X>pre->Data){
pre->Right=q;
}
else{
pre->Left=q;
}
}
return BST;
}
插入代码B:
BinTree Insert( BinTree BST, ElementType X ){
if(BST==NULL){
BST=(BinTree)malloc(sizeof (struct TNode));
BST->Data=X;
BST->Left=BST->Right=NULL;
}
else{
if(X>BST->Data){
BST->Right=Insert(BST->Right,X);
}
else if(X<BST->Data){
BST->Left=Insert(BST->Left,X);
}
}
return BST;
}
删除代码:
BinTree Delete( BinTree BST, ElementType X ){
if(!BST){
printf("Not Found\n");
return NULL;
}
if(X<BST->Data)
BST->Left=Delete(BST->Left,X);
else if(X>BST->Data)
BST->Right=Delete(BST->Right,X);
else{
if(BST->Right==NULL)
return BST->Left;
if(BST->Left==NULL)
return BST->Right;
BinTree minNode=FindMin(BST->Right);
BST->Data=minNode->Data;
BST->Right=Delete(BST->Right,minNode->Data);
}
return BST;
}
查找代码:
Position Find( BinTree BST, ElementType X ){
if(!BST)
return NULL;
if(BST->Data==X)
return BST;
else if(X<BST->Data)
return Find(BST->Left,X);
else
return Find(BST->Right,X);
}
Position FindMin( BinTree BST ){
if(BST){ //需要判断是否是空树,否则NULL无法实现“BST->Left”
while(BST->Left){
BST=BST->Left;
}
}
return BST;
}
Position FindMax( BinTree BST ){
if(BST){
while(BST->Right){
BST=BST->Right;
}
}
return BST;
}