mooc二叉查找树
2017-03-26 本文已影响0人
有苦向瓜诉说
<a href='http://blog.csdn.net/wanmeiwushang/article/details/51921821'>参考博客链接</a>
自己写的代码:
BinTree Insert( BinTree BST, ElementType X )
{
if(!BST){
BST=(BinTree)malloc(sizeof(struct TNode));
BST->Data=X;
BST->Left=BST->Right=NULL;
return BST;
}
if(X<BST->Data){
BST->Left=Insert(BST->Left,X);
}
else if(X>BST->Data){
BST->Right=Insert(BST->Right,X);
}
return BST;
}
BinTree Delete( BinTree BST, ElementType X )
{
Position Tmp;
if(!BST){
printf("Not Found\n");
return BST;
}
if(X<BST->Data) BST->Left=Delete(BST->Left,X);
else if(X>BST->Data) BST->Right=Delete(BST->Right,X);
else{
if(BST->Left&&BST->Right){
Tmp=BST->Right;
while(Tmp->Left){
Tmp=Tmp->Left;
}
BST->Data=Tmp->Data;
BST->Right=Delete(BST->Right,Tmp->Data);
}
else{
Tmp=BST;
if(!BST->Left){
BST=BST->Right;
}
else if(!BST->Right){
BST=BST->Left;
}
free(Tmp);
}
}
return BST;
}
Position Find( BinTree BST, ElementType X ) // 用递归比较好用
{
if(!BST) return NULL;
if(X==BST->Data) return BST;
else if(X>BST->Data) return Find(BST->Right,X);
else if(X<BST->Data) return Find(BST->Left,X);
}
Position FindMin( BinTree BST )
{
if(!BST) return NULL;
while(BST->Left){
BST=BST->Left;
}
return BST;
}
Position FindMax( BinTree BST )
{
if(!BST) return NULL;
while(BST->Right){
BST=BST->Right;
}
return BST;
}