# 二叉查找树的部分例程

550人阅读 评论(0)

searchtree.h

#ifndef SEARCHTREE_H_INCLUDED
#define SEARCHTREE_H_INCLUDED

typedef  int ElementType;
struct treenode;
typedef  struct treenode *Position;
typedef  Position  SearchTree;
struct  treenode
{
ElementType  data;
SearchTree  left;
SearchTree  right;
};

SearchTree  MakeEmpty(SearchTree  T);
Position  Find(ElementType  X,SearchTree  T);
Position  FindMin(SearchTree  T);
Position  FindMax(SearchTree  T);
SearchTree  Insert(ElementType  X,SearchTree  T);
SearchTree  Delete(ElementType  X,SearchTree  T);

#endif // SEARCHTREE_H_INCLUDED


searchtree.c

#include  <stdio.h>
#include  <malloc.h>
#include   "searchtree.h"

SearchTree  MakeEmpty(SearchTree  T)
{
if(T!=NULL)
{
MakeEmpty(T->left);
MakeEmpty(T->right);
free(T);
}

return  NULL;
}

Position  Find(ElementType  X,SearchTree  T)
{
if(T==NULL)
return  NULL;
else if(X <T->data)
return  Find(X, T->left);
else if(X >T->data)
return  Find(X,T->right);
else
return  T;
}

Position  FindMin(SearchTree  T)
{
if(T==NULL)
return  NULL;
else  if(T->left ==NULL)
return T;
else
return FindMin(T->left);
}

Position  FindMax(SearchTree  T)
{
if(T!=NULL)
while(T->right!=NULL)
T=T->right;

return T;
}

SearchTree  Insert(ElementType  X,SearchTree  T)
{
if(T==NULL)
{
T=(SearchTree)malloc(sizeof(struct treenode));
if(T==NULL)
printf("Error: out of space!!!");
else
{
T->data=X;
T->left =T->right =NULL;
}
}
else  if(X <T->data)
{
T->left =Insert(X, T->left);
}
else  if(X >T->data)
{
T->right  =Insert(X , T->right);
}

return T;   /**< don't forget  this line!!!! */
}

SearchTree  Delete(ElementType  X,SearchTree  T)
{
Position  temp;

if(T==NULL)
printf("Error: not this element!!!");
else if(X <T->data)
T->left =Delete(X, T->left);   /**<  Go left */
else if(X >T->data)
T->right =Delete(X, T->right);  /**< go  right */
else     /**< find  element,delete it */
{
if(T->left && T->right)
{
temp =FindMin(T->right) ;  /**< the minest value  in right subtree */
T->data =temp->data;
T->right =Delete(T->data, T->right);   /**< 删去右子树中的最小节点，可以编写deletemin函数以提高效率 */
}
else
{
temp =T;
if(T->left ==NULL)
T=T->right;
else
T=T->left;
free(temp);
}
}

return  T;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：67635次
• 积分：1443
• 等级：
• 排名：千里之外
• 原创：73篇
• 转载：22篇
• 译文：0篇
• 评论：12条
评论排行
最新评论