tree

二叉树,层序、先序遍历2
2007-06-07 08:24 A.M.

Tree *InitTree(int h,int t,int w)

{

   char ch;

   int n;/*自动建立时随机赋值判断是否是NULL的标志*/

   Tree *node;

   if(way=='2')/*手动建立需要自己输入*/

      scanf("%c",&ch);

   else/*自动建立的赋值*/

   {

      n=random(5);

      if(n==0&&nodeNUM>=3)/*随机赋值时候确保自动建立的二叉树有三个结点*/

     ch='.';

      else

     ch=65+random(25);

   }

   if(ch=='.')/*输入空格代表NULL*/

      return NULL;

   else

   {

      if(h==6||nodeNUM==26)/*如果树的层次已经到5或者结点树到达26个就自动返回NULL*/

     return NULL;

      node=(Tree*)malloc(sizeof(Tree));

      node->data=ch;

      node->x=t;/*树的x坐标是传递过来的横坐标*/

      node->y=h*50;/*树的y坐标与层次大小有关*/

      nodeNUM++;

      node->lchild=InitTree(h+1,t-w,w/2);

      node->rchild=InitTree(h+1,t+w,w/2);

   }

   return node;

}

/*用图形显示创建好的树*/

void DrawTree(Tree *t)

{

   if(t!=NULL)

   {

      setcolor(BLACK);

      setfillstyle(SOLID_FILL,BLACK);

      fillellipse(t->x,t->y,9,9);

      setcolor(WHITE);

      circle(t->x,t->y,10); /*画圆*/

      sprintf(str,"%c",t->data);/*将内容转换成字符串输出*/

      outtextxy(t->x-3,t->y-2,str);

      if(t->lchild!=NULL)/*左子树*/

      {

     line(t->x-5,t->y+12,t->lchild->x+5,t->lchild->y-12);

     DrawTree(t->lchild);

      }

      if(t->rchild!=NULL)/*右子树*/

      {

     line(t->x+5,t->y+12,t->rchild->x-5,t->rchild->y-12);

     DrawTree(t->rchild);

      }

   }

}

/*遍历时显示每个结点的过程*/

void DrawNode(Tree *t,int color)

{

   setcolor(YELLOW);

   setfillstyle(SOLID_FILL,YELLOW);

   fillellipse(t->x,t->y,10,10);

   setcolor(RED);

   sprintf(str,"%c",t->data);/*将内容转换成字符串输出*/

   outtextxy(t->x-3,t->y-2,str);

   setcolor(color);

   outtextxy(s.x,s.y,str);

   setcolor(RED);

   sprintf(str,"%d",s.num);/*将遍历次序用数字显示在树的结点上*/

   outtextxy(t->x-3,t->y-20,str);

   s.num++;

   sleep(1);

}

/*前序遍历*/

void Preorder(Tree *t)

{

   if(t!=NULL)

   {

      s.x+=15;

      DrawNode(t,GREEN);

      Preorder(t->lchild);

      Preorder(t->rchild);

   }

}

/*中序遍历*/

void Midorder(Tree *t)

{

   if(t!=NULL)

   {

      Midorder(t->lchild);

      s.x+=15;

      DrawNode(t,YELLOW);

      Midorder(t->rchild);

   }

}

/*后序遍历*/

void Posorder(Tree *t)

{

   if(t!=NULL)

   {

      Posorder(t->lchild);

      Posorder(t->rchild);

      s.x+=15;

      DrawNode(t,BLUE);

   }

}

/*图形初始化*/

void Init()

{

   int gd=DETECT,gm;

   initgraph(&gd,&gm,"c://tc");

   cleardevice();

   setcolor(YELLOW);

   outtextxy(250,10,"anykey to continue");

   setcolor(RED);

   outtextxy(20,300,"preorder");

   outtextxy(20,350,"midorder");

   outtextxy(20,400,"posorder");

   getch();

}

/*图形关闭*/

void Close()

{

   getch();

   closegraph();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值