二叉查找树性质:对于数中的每个节点X,其左子树中所有关键字值小于X关键字值,而其右子树所有关键字值大于X的关键字值
二叉查找树的创建,查找,插入,删除:
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
SearchTree MakeEmpty(SearchTree Tree);
Position Find(ElementType X,SearchTree Tree);
Position FindMin(SearchTree Tree);
Position FindMax(SearchTree Tree);
SearchTree Insert(ElementType X,SearchTree Tree);
SearchTree Delete(ElementType X,SearchTree Tree);
struct TreeNode
{
ElementType Element;
SearchTree Left;
SearchTree Right;
};
//建立一棵空树
SearchTree MakeEmpty(SearchTree Tree){
if(Tree!=NULL){
MakeEmpty(Tree->Left);
MakeEmpty(Tree->Right);
free(Tree);
}
return NULL;
}
//返回指向树中具有数据X的节点的指针
Position Find(ElementType X,SearchTree Tree){
if(Tree==NULL)
return NULL;
if(X<Tree->Element)
Find(X,Tree->Left);//在左子树继续查找
else if(X>Tree->Element)
Find(X,Tree->Right);//在右子树继续查找
else//X==Tree->Element
return Tree;
/*while(Tree){//迭代法
if(X<Tree->Element)
Tree=Tree->Left;
else if(X>Tree->Element)
Tree=Tree->Right;
else
return Tree;
}
return NULL;
*/
}
//返回指向树中最小元节点的指针
Position FindMin(SearchTree Tree){
if(Tree==NULL)
return NULL;
else if(Tree->Left==NULL)
return Tree;
else
FindMin(Tree->Left);
/*非递归方法
if(Tree!=NULL)
while(Tree->Left!=NULL)
Tree=Tree->Left;
return Tree;
*/
}
//返回指向树中最大元节点的指针
Position FindMax(SearchTree Tree){
if(Tree==NULL)
return NULL;
else if(Tree->Right==NULL)
return Tree;
else
return FindMax(Tree->Right);
/*非递归方法
if(Tree!=NULL)
while(Tree->Right!=NULL)
Tree=Tree->Right;
return Tree;
*/
}
//将X插入到树中
SearchTree Insert(ElementType X,SearchTree Tree){
if(Tree==NULL){
Tree=(SearchTree)malloc(sizeof(struct TreeNode));
if(Tree==NULL)
FatalError("out of space");
else{
Tree->Element=X;
Tree->Left=NULL;
Tree->Right=NULL;
}
}
else{
if(X>Tree->Element)
Tree->Right=Insert(X,Tree->Right);
else if(X<Tree->Element)
Tree->Left=Insert(X,Tree->Left);
else
return Tree;
}
}
//删除节点X
SearchTree Delete(ElementType X,SearchTree Tree){
Position TmpNode;
if(Tree==NULL)
Error("element not found");
else if(X<Tree->Element)
Tree->Left=Delete(X,Tree->Left);
else if(X>Tree->Right)
Tree->Right=Delete(X,Tree->Right);
//说明要删除的节点有两个儿子
/*首先找到其右子树中的最小数据并代替该节点的数据,然后
再用递归删除那个右子树中最小的数据(因为右子树中最小的
节点不可能有左儿子,所以第二次删除更容易)
*/
else if(Tree->Left&&Tree->Right){
TmpNode=FindMin(Tree->Right);
Tree->Element=TmpNode->Element;
Tree->Right=Delete(Tree->Element,Tree->Right);
}
//最后一种是要删除的节点有一个或者没有儿子
/*如果被删除的节点是树叶,可以直接删除,如果有一个儿子,那
么调整其父节点的指向即可
*/
else{
TmpNode=Tree;
if(Tree->Left==NULL)
Tree=Tree->Right;
else if(Tree->Right==NULL)
Tree=Tree->Left;
free(TmpNode);
}
return Tree;
}