zoukankan      html  css  js  c++  java
  • 二叉查找树

    结构体声明:

    struct TreeNode;
    typedef struct TreeNode *Position;
    typedef struct TreeNode *SearchTree;
    
    struct TreeNode
    {
        ElementType Element;
        SearchTree Left;
        SearchTree Right;
    };   

    建立空树:

    SearchTree MakeEmpty(SearchTree T)
    {
        if (T!=NULL)
        {
            MakeEmpty(T->Left);
            MakeEmpty(T->Right);
            free(T);
        }  
    } 

    查找操作:

    Position Find(ElementType X, SearchTree T)
    {
        if (T==NULL)
        {
            return NULL;
        }
        if (x < T->Element)
            return Find(X, T->Left);
        else if (x > T->Element)
            return Find(X, T->Right);
        else
            return T;
    }

    FindMin实现:

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

    FindMax实现:

    Position FindMax(SearchTree T)
    {
        if (T!=NULL)
            while(T->Right!=NULL)
                T=T->Right;
        return T;
    }

    Insert操作:

    SearchTree Insert(ElementType X, SearchTree T)
    {
        if (T==NULL)
        {
            T = malloc(sizeof(struct TreeNode));
            if (T==NULL)
            {
                FataError("out of space");
            }
            else
            {
                T->Element = X;
                T->Left = T->Right = NULL;
            }
        }
        else if (X<T->Element)
            T->Left = Insert(X, T->Left);
        else if (X>T->Element)
            T->Right = Insert(X, T->Right);
    
        return T;
    }

    Delete操作:

     1 SearchTree Delete(ElementType X, SearchTree T)
     2 {
     3     Position TmpCell;
     4     if (T==NULL)
     5     {
     6        Error("Element not found");
     7     }
     8     else if (X<T->Element)
     9         T->Left = Delete(X, T->Left);
    10     else if (X>T->Element)
    11         T->Right = Delete(X, T->Right);
    12     else if (T->Left && T->Right)
    13     {
    14         TmpCell = FineMin(T->Right);
    15         T->Element = TmpCell->Element;
    16         T->Right = Delete(T->Element, T->Right);
    17     }    
    18     else
    19     {
    20         TmpCell = T;
    21         if (T->Left==NULL);
    22             T= T->Right;
    23         else if (T->Right==NULL);
    24             T= T->Left;
    25         free(TmpCell);
    26     }    
    27     return T;
    28 }
  • 相关阅读:
    使用ForEach循环控制器对返回参数进行多次调用
    html基础
    Eclipse使用github并开启命令行
    vim
    使用Jsoup爬取网站图片
    YUM
    javaagent项目中使用
    Linux基础三---打包压缩&vim&系统的初始化和服务
    linux 基础二---用户群租权限
    Linux 基础一---操作系统&常用命令
  • 原文地址:https://www.cnblogs.com/m2492565210/p/7482809.html
Copyright © 2011-2022 走看看