二叉树的创建及中序遍历

 #include<stdio.h>  
  #include<stdlib.h>  
  typedef   char   datatype;//二叉树结点的信息类型  
  typedef   enum{Link,Thread}   tagtype;//结点域是链接还是线索的判断  
  typedef   struct   BiTNode//二叉树结点类型  
  {  
  struct   BiTNode   *lchild,*rchild;  
  tagtype   LTag,RTag;  
  datatype   data;  
  }BiTNode;  
  int   InThreading(BiTNode   *thr);  
  BiTNode   *pre,*thr;//thr是线索二叉树的头指针  
   
  BiTNode   *CreateBiTree()//先序递归法建树  
  {  
  char   x;  
  BiTNode   *t;  
  scanf("%c",&x);  
  if   (x   ==   '   ')t   =   NULL;  
  else  
  {  
  if   (!(t   =   (BiTNode   *)malloc(sizeof(BiTNode))))exit(-1);  
  t->data   =   x;//建立节点  
  if   ((t->lchild   =   CreateBiTree())   !=   NULL)  
  {  
  t->LTag   =   Link;//建左子树,并给用左子树的结点的LTag域赋Link值表示是链接  
  }  
  if   ((t->rchild   =   CreateBiTree())   !=   NULL)  
  {  
  t->RTag   =   Link;//建右子树,并给用右子树的结点的RTag域赋Link值表示是链接  
  }  
  }  
  return   t;  
  }  
   
  int   InOrderThr(BiTNode   *t)//中序遍历二叉树,并将其线索化,thr为其lchild指向根节点的树的头结点,用于构建一棵双向线索树  
  {  
  thr->LTag   =   Link;//构造头结点  
  thr->RTag   =   Thread;  
  thr->rchild   =   thr;  
  if   (!t)  
  {  
  thr->lchild   =   thr;  
  }  
  else  
  {  
  thr->lchild   =   t;  
  pre   =   thr;//pre指针用于指向结点的前驱  
  InThreading(t);//线索化  
  pre->rchild   =   thr;//线索化后续工作  
  pre->RTag   =   Thread;  
  thr->rchild   =   pre;  
  }  
  return   1;  
  }  
   
  int   InThreading(BiTNode   *t)//递归法线索化二叉树  
  {  
  if   (t)  
  {  
  InThreading(t->lchild);//线索化左子树  
  if   (!t->lchild)//左子树为空,则用左链指向其前驱即pre指针  
  {  
  t->LTag   =   Thread;  
  t->lchild   =   pre;  
  }  
  if   (!pre->rchild)//右子树为空,则pre指针指向结点的后继为当前结点  
  {  
  pre->RTag   =   Thread;  
  pre->rchild   =   t;  
  }  
  pre   =   t;  
  InThreading(t->rchild);//线索化右子树  
  }  
  return   1;  
  }  
   
  int   InOrderTra(BiTNode   *thr)//中序非递归遍历线索二叉树,thr为二叉树的头结点非根结点  
  {  
  BiTNode   *p;  
  p   =   thr->lchild;  
  printf("中序非递归遍历线索二叉树的序列为:/n");  
  while   (p   !=   thr)  
  {  
  while   (p->LTag   ==   Link)//顺着左子树链找开始遍历的结点  
  {  
  p   =   p->lchild;  
  }  
  printf("%c",p->data);//访问无左子树的结点  
  while   (p->RTag   ==   Thread   &&   p->rchild   !=   thr)//顺线索访问其后序结点  
  {  
  p   =   p->rchild;  
  printf("%c",p->data);  
  }  
  p   =   p->rchild;  
  }  
  return   1;  
  }  
   
  void   main()  
  {  
  BiTNode   *t;  
  if   (!(thr   =   (BiTNode   *)malloc(sizeof(BiTNode))))exit(-1);  
  printf("请输入构建二叉树的字符序列,用空格构造空子树:/n");  
  t   =   CreateBiTree();  
  InOrderThr(t);  
  InOrderTra(thr);  
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值