二叉树建立与查找

#include<stdio.h>
typedef struct tree{
struct tree *left;
int data;
struct tree *right;
}str_tree,*link_tree;
link_tree creat_tree(link_tree boot,int *p,int len)
{
int i;
link_tree q;
link_tree pnode;
link_tree new;
q=boot;
q->data=p[1];
for(i=2;i<len;i++)
 {
  q=boot;
  new=(link_tree)malloc(sizeof(str_tree));
  new->data=p[i];
  new->left=NULL;
  new->right=NULL;
    while(q!=NULL)
    {
    pnode=q;
    if(new->data<q->data)
          q=q->left;
     else
         q=q->right;
        
     }
    if(pnode->data>new->data)
        pnode->left=new;
     else
        pnode->right=new;  
   }

return boot;
}
//***********************************forder()*********************
void forder(link_tree boot)
{
if(boot!=NULL)
   {
   printf(“%d/t”,boot->data);
   forder(boot->left);
   forder(boot->right);
   }
}
//*************************************morder()********************
void morder(link_tree boot)
{
  if(boot!=NULL)
  {
  forder(boot->left);
  printf(“%d/t”,boot->data);
  forder(boot->right);
  }
}
//******************************lorder()**************************
void lorder(link_tree boot)
{
if(boot!=NULL)
  {
  lorder(boot->left);
  lorder(boot->right);
  printf(“%d/t”,boot->data);
  }
}

//***************************find()*****************************
void find(link_tree boot,int num)
{
  if(boot!=NULL)
   {if(boot->data==num)
      printf(” find the number!/n”);
   else
      if(num<boot->data)
        {find(boot->left,num); 
         }
      else
        {find(boot->right,num);
        }
   }
if(boot==NULL)
 printf(“NO SUCH NUMBER!/n”);
}
//***********************************lfind()*********************
link_tree lfind(link_tree boot,int num)
{
link_tree p;
p=boot;
while(p!=NULL)
  {
   if(p->data==num)
        return p;
   else
       if(num<p->data)
           p=p->left;
        else
            p=p->right;
  }
return NULL;
}

//**************************************main()********************
main()
{

int i,num;
link_tree p;
link_tree boot;
link_tree findnum;
boot=(link_tree)malloc(sizeof(str_tree));
boot->data=0;
boot->left=NULL;
boot->right=NULL;
int a[9]={0,6,4,7,3,5,8,2,9};
//for(i=1;i<100;i++)
//   a[i]=random()%10
int length=9;
boot=creat_tree(boot,a,length);
p=boot;
printf(“the midorder is :/n”);
morder(boot);
printf(“/n”);
printf(“the forder is:/n”);
forder(boot);
printf(“/n”);
printf(“the lorder is:/n”);
lorder(boot);
printf(“/n”);
printf(“input you want to search number:”);
scanf(“%d”,&num);
find(boot,num);
findnum=lfind(boot,num);
if(findnum==NULL)
   printf(“NO THIS NUMBER!/n”);
else
   printf(“FIND!/n”);
}

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