线索二叉树的线索化和遍历

第一次在博客园写博客,因为在准备找工作,复习数据结构和算法部分,现在将实现的代码贴出来,欢迎勘误。

  1 //线索二叉树的相关操作
  2 #include<stdio.h>
  3 #include<malloc.h>
  4 typedef char TElemtype;
  5 typedef enum {Link,Thread} PointerTag;//Link==0,Thread==1,线索
  6 typedef struct BiThrNode{
  7         TElemtype data;
  8         struct BiThrNode *lchild,*rchild;//左右指针
  9         PointerTag LTag,Rtag; 
 10 }BiThrNode,*BiThrTree; 
 11  BiThrTree pre=NULL;//定义成全局变量 
 12 
 13 void InThreading(BiThrTree p)
 14 {
 15   if(p){
 16         InThreading(p->lchild);//左子树线索化 
 17         if(!p->lchild)//前驱线索树 
 18         {
 19          p->LTag=Thread;
 20          p->lchild=pre;
 21          printf("%c\n",p->data);
 22         } 
 23         if(!pre->rchild)//后继线索 
 24         {
 25           pre->Rtag=Thread;
 26           pre->rchild=p;
 27           printf("%c\n",p->data);
 28         }
 29         pre=p;
 30         InThreading(p->rchild); 
 31         }
 32 }
 33 //中序线索化二叉树
 34 BiThrTree inOrderThreading(BiThrTree Thrt,BiThrTree T)
 35 {
 36  Thrt=(BiThrTree)malloc(sizeof(BiThrNode));
 37  printf("%d\n",Thrt);
 38  if(!Thrt) return -1;
 39  Thrt->LTag=Link;
 40  Thrt->Rtag=Thread;
 41 
 42  if(!T)
 43  Thrt->lchild=Thrt;
 44  else{
 45       Thrt->lchild=T;
 46       pre=Thrt;
 47       InThreading(T); 
 48       pre->rchild=Thrt;
 49       pre->Rtag=Thread;
 50       Thrt->rchild=pre;
 51       
 52       }
 53       printf("%c\n",Thrt->lchild->data);
 54       printf("完全实现啦!"); 
 55  return Thrt;
 56 //返回指针指向的值。
 57 } 
 58 
 59 int inOrderTraverse(BiThrTree Thrt)
 60 {
 61     printf("进入到inOrderTraverse()");
 62     if(Thrt)
 63          printf("Thrt不为空\n");
 64     printf("%c\n",Thrt->lchild->data);
 65     BiThrTree p=Thrt->lchild;
 66    // printf("adfff");
 67     while(p!=Thrt)
 68     {
 69      while(p->LTag==Link)
 70      p=p->lchild;
 71      printf("%c",p->data);
 72      while(p->Rtag==Thread&&p->rchild!=Thrt)
 73      {
 74       p=p->rchild;
 75       printf("%c",p->data);
 76      }
 77      p=p->rchild;
 78     }
 79     
 80 return 0;
 81 }
 82 
 83 //使用先序遍历建立二叉树
 84 BiThrTree CreateBiTree()
 85 {
 86 
 87     char ch;
 88     scanf("%c",&ch);
 89     getchar();
 90    if(ch!='#'){
 91    
 92    printf("输入当前节点的值:");
 93    printf("%c\n",ch); 
 94    BiThrTree Thrt=(BiThrTree)malloc(sizeof(BiThrNode));
 95    Thrt->data=ch; 
 96    Thrt->Rtag=Thrt->LTag=Link;
 97    Thrt->lchild=CreateBiTree();
 98    Thrt->rchild=CreateBiTree(); 
 99    return Thrt;
100    }else
101    return NULL; 
102 } 
103 int main()
104 {
105 BiThrTree T=CreateBiTree();
106 BiThrTree Thrt;//创建更外的根节点 
107 printf("之前的值:%d\n",Thrt);
108 Thrt=inOrderThreading(Thrt,T);
109 printf("%d\n",Thrt);
110 if(Thrt)
111    printf("之后的值:hello world!\n");
112    printf("%c\n",Thrt->lchild->data); 
113 inOrderTraverse(Thrt);
114 system("pause");
115 } 
原文地址:https://www.cnblogs.com/moshang/p/3766879.html