二叉树

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct BiTNode
{
    char date[16];
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

void INS(BiTree &Q,char *a)
{
    BiTree S;
    if(!Q)
    {
        S=new BiTNode;
        strcpy(S->date,a);
        S->lchild=S->rchild=NULL;
        Q=S;
    }
    else if(strcmp(Q->date,a))
        INS(Q->lchild,a); 
    else if(strcmp(a,Q->date))
        INS(Q->rchild,a);
}

//创建二叉树
void creB(BiTree &Q)
{
    Q=NULL;//chu shi hua
    char a[16];
    while(~scanf("%s",a)&&a[0]!='#')
    {
        INS(Q,a);
    }
}


void priB(BiTree Q)
{
    if(Q)
    {
        priB(Q->lchild);
        priB(Q->rchild);
        printf("%s ",Q->date);
    }
}
int main()
{
    BiTree T;
    creB(T);
    priB(T);
    return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct BiTNode
{
  int d;
  char date[16];
  struct BiTNode *lchild,*rchild;
} BiTNode,*BiTree;
char key[16];

void INS(BiTree &Q,char *a,int n)
{
  BiTree S;
  if(!Q)
  {
    S=new BiTNode;
    strcpy(S->date,a);
    S->d=n;
    S->lchild=S->rchild=NULL;
    Q=S;
  }
  else if(strcmp(Q->date,a))
    INS(Q->lchild,a,n);
    else if(strcmp(a,Q->date))
    INS(Q->rchild,a,n);
  }

//创建
void creB(BiTree &Q)
{
  Q=NULL;//chu shi hua
  char a[16];
  int i=0;
  while(~scanf("%s",a)&&a[0]!='#')
  {
    INS(Q,a,i++);
  }
}


void priB(BiTree Q)
{
  if(Q)
  {
    priB(Q->lchild);
    priB(Q->rchild);
    printf("%s ",Q->date);
  }
}

BiTree fin(BiTree Q,char *x)
{
  BiTree p=NULL;
  if(Q)
  {
    if(strcmp(Q->date,key)==0)
      p=Q;
    else if(strcmp(Q->date,key)<0)
      p=fin(Q->rchild,key);
    else
      p=fin(Q->lchild,key);
  }
  return p;
}

int main()
{
  BiTree K;
  BiTree T;
  creB(T);
  priB(T);
  printf("\n");
  while(scanf("%s",key)&&key[0]!='#')
  {
    K=fin(T,key);
    if(K)
    printf("%s\n",K->date);
  }
  return 0;
}
posted @ 2021-06-21 11:14  Mr-Yao  阅读(31)  评论(0编辑  收藏  举报