孤月天心

无限野云风卷尽,一轮孤月照天心

二叉查找树的部分例程

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;
}


阅读更多
个人分类: 数据结构与算法
上一篇AVL平衡树的实现
下一篇快速排序
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭