二叉排序树操作

数据结构:

  struct BinTreeNode;

  typedef struct BinTreeNode * pBinTreeNode;

  struct BinTreeNode

  {

    KeyType key;    //元素的关键码

    DataType othre;    //元素的属性

    PBinTreeNode llink,rlink;

  };            //字典的存储

  typedef struct BinTreeNode *BinTree;

  typedef BinTree * PBinTree;  //字典的指针

检索算法:

  int searchNode(PBinTree ptree,KeyType key,PBinTreeNode *position)

  {

    PBinTreeNode p,q;

    p = *ptree;

    q = p;

    while(p != NULL)

    {

      q = p;

      if(p->key == key)

      {

        *position = p;

        return TRUE;

      }

      else if(p->key>key)

        p = p->llink;

        else

          p = p->rlink;

    }

    *position = q;

    return FALSE;

  }

插入算法:

  void insertNode(PBinTree ptree,KeyType key)

  {

    PBinTreeNode p,position;

    if(searchNode(ptree,key,&position) == TRUE)

      return;

    p = (PBinTreeNode)malloc(sizeof(struct BinTreeNode));

    p->key = key;

    p->llink = p->rlink = NULL;

    if(position == NULL)

      *ptree = p;

    else if(key<position->key)

      position->llink = p;

      else

        position->rlink = p;

  }

删除结点:

  if(*p无左子女)

    用*p的右子女代替*p;

  else

  {

    找*p的左子树中最右下结点*r;

    用*r的右指针指向*p的右子女;

    用*p的左子女代替*p;

  }

posted @ 2012-09-12 14:41  毛毛hhmm  阅读(294)  评论(0编辑  收藏  举报