查找与二叉排序树的建立与查找实现

实验内容

(1)、顺序查找的设计与实现;

(2)、顺序表中的折半查找的设计与实现;

(3)、二叉排序树的建立与查找实现;

///////////顺序查找,折半查找~~~~二叉排序树的建立,查找////////////////////
#include<stdio.h>

typedef int KeyType;

typedef struct{
       KeyType key;
}DataType;

typedef struct{
        DataType *elem;
        int length;
}SeqTable;

typedef struct BinSTreeNode{
         DataType elem;
         struct BinSTreeNode *lchild,*rchild;
}*BinSTree;

int SeqSearch(SeqTable s,KeyType k)
{
    int i;
    for(i=0;i<s.length;i++)
    if(s.elem[i].key==k)
    return(i);
    return(-1);
}

int BinSearch(SeqTable s,KeyType k)                /*顺序查找*/
{
   int low,high,mid;
   low=0;
   high=s.length-1;
   while(low<=high)
   {
      mid=(low+high)/2;
      if(s.elem[mid].key==k)  return(mid);
      else if(s.elem[mid].key>k) high=mid-1;
      else low=mid+1;
  }

  return -1;

}
void InOrder(BinSTree t)                             /*中序遍历*/
{
   if(t)
   {
     InOrder(t->lchild);
     printf(“%d “,t->elem.key);
     InOrder(t->rchild);
   }
}
int BSTreeSearch(BinSTree t,KeyType k)             /*二叉树的查找*/
{
   while(t)
   {
     if(t->elem.key==k) return 1;
     else  if(t->elem.key>k)  t=t->lchild;
     else if(t->elem.key<k)  t=t->rchild;
   }
   return 0;
}

BinSTree BSTreeInsert(BinSTree bt,KeyType k)     /*二叉树的插入*/
{
   BinSTree p;

     if(bt==NULL)
     {
       p=(BinSTree)malloc(sizeof(struct BinSTreeNode));
       p->elem.key=k;p->rchild=p->lchild=NULL;
       return p;
     }
      else if(bt->elem.key==k) return bt;
      else if(bt->elem.key>k)
        bt->lchild=BSTreeInsert(bt->lchild,k);
      else
        bt->rchild=BSTreeInsert(bt->rchild,k);
      return bt;

}
BinSTree CreateBSTree()                             /*二叉树的建立*/
{
    BinSTree s,t;
    KeyType k,endflag=0;
    t=NULL;
    printf(“please input the key:/n”);
    scanf(“%d”,&k);
    while(k!=endflag)
    {
       s=(BinSTree)malloc(sizeof(struct BinSTreeNode));
       s->rchild=s->lchild=NULL;
       s->elem.key=k;
       t=BSTreeInsert(t,k);
       scanf(“%d”,&k);
    }
    return t;
}

main()
{
   SeqTable s;
   BinSTree t;
   int i,k;
   printf(“please input the length of s:”);
   scanf(“%d”,&s.length);
   printf(“/nplease input the elem of the seqtable(s):”);
   for(i=0;i<s.length;i++)
   scanf(“%d”,&(s.elem[i].key));
   printf(“/nplease the searchelem(k): “);
   scanf(“%d”,&k);
   printf(“the k’s position after SeqSearch is %d/n”,SeqSearch(s,k));
   printf(“the k’s position after BinSearch is %d/n”,BinSearch(s,k));

   t=CreateBSTree();
   printf(“/ninput the key:/n”);
   scanf(“%d”,&k);
   if(BSTreeSearch(t,k))
   printf(“success/n”);
   else printf(“fail/n”);
   printf(“the betree after inorder is:/n”);
   InOrder(t);

   getch();
}

 

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/qiance/article/details/1659777
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞