Chinaunix首页 | 论坛 | 博客
  • 博客访问: 164809
  • 博文数量: 14
  • 博客积分: 255
  • 博客等级: 二等列兵
  • 技术积分: 621
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-27 13:12
个人简介

热爱推理

文章分类
文章存档

2015年(2)

2014年(1)

2013年(5)

2011年(1)

2010年(5)

我的朋友

分类: C/C++

2010-12-21 17:56:51

struct TreeNode
{
       int Element;
       SearchTree Left;
       SearchTree Right;
};

typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;

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

Position
Find( int X, SerachTree T )
{
      if( T == NULL )
      {
          printf( "EmptyTree!No such Position" );
          return NULL;
      }
      if( X < T->Element )
          return Find( int X, T->Left );
      else
      if( X > T->Element )
          return Find( int X, T->Right );
      else
          return T;
}

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

Position
FindMax( SearchTree T )
{
         if( T == NULL )
         {
             printf( "EmptyTree!" );
             return NULL;
         }
         else
         if( T->Right == NULL )
             return T;
         else
             return FindMax( T->Right );
}

SearchTree
Insert( int X, SearchTree T )
{
        if( T == NULL )
        {
            T = malloc( sizeof( struct TreeNode ) );
            if( T == NULL )
                printf( "OUT OF SPACE!" ):
            else
            {
                T->Element = X;
                T->Left = T->Right = NUL;
            }
        }
        else
        if( X < T->Element )
            T->Left = Insert( X, T->Left );
        else
        if( X > T->Element )
            T->Right = Insert( X, T->Right );
        else
            return T;
}

SearchTree
Delete( int X, SearchTree T )
{
        Position TmpCell;
        
        if( T == NULL )
            printf( "Element not found!" );
        else
        if( X < T->Element )
            T->Left = Delete( X, T->Left );
        else
        if( X > T->Element )
            T->Right = Delete( X, T->Right );
        else
        if( T->Left && T->Right )
        {
            TmpCell = FindMin( T->Right );
            T->Element = TmpCell->Element;
            T->Right = Delete( T->Element, T->Right );
        }
        else
        {
            TmpCell = T;
            if( T->Left == NULL )
                T = T->Right;
            else
            if( T->Right == NULL )
                T = T->Right;
            free( TmpCell );
        }
        
        return T;
}
          
           


特意没有写上注释,以后自己有空就来看看,这是二叉搜索树的结构与运算性质
阅读(1897) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~