線索二叉樹的創建

使用平臺Ubuntu+Code::Blocks(GCC)node

線索二叉樹的意思是:利用二叉樹上節點的空指針指向其前驅或者後繼。數據結構課本上說:在某程序中所用二叉樹需常常遍歷或查找結點在遍歷所得線性序列中的前驅和後繼,則應採用線索鏈表做爲存儲結構。數據結構

程序中有一個頭結點thrdBase,其爲二叉樹外的結點,結點沒有數據信息,其lChild指向二叉樹的根結點,其rChild指向中序遍歷時訪問的最後一個結點。而且讓中序序列的第一個結點的lChild和最後一個結點的rChild指向這個頭結點。這樣作好處在於:至關與創建了一個雙向線索鏈表,既能夠從第一個結點起順序日後進行遍歷,也可從最後一個結點順着前驅進行遍歷。ide

 

代碼爲按先序序列創建的二叉樹,而後進行中序創建線索thread。spa

(書中有部分代碼,書爲嚴蔚敏和吳偉民編著的c語言版數據結構)指針

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #define OK 1
  4 #define ERROR 0
  5 #define LINK 0
  6 #define THREAD 1
  7 
  8 //the type of data
  9 typedef char DataType;
 10 typedef int Status;
 11 
 12 //keep the information of node
 13 typedef struct BiThrNode
 14 {
 15     DataType data;
 16     struct BiThrNode *lChild,*rChild;
 17     int lTag,rTag;
 18 }BiThrNode,*BiThrTree;
 19 BiThrTree pre = NULL;
 20 
 21 //preorder the tree
 22 Status createBiTree(BiThrTree *T)
 23 {
 24     char ch;
 25     scanf("%c",&ch);
 26     if(ch == '\n'|| ch == '\t')
 27     {
 28         return OK;
 29     }
 30 
 31     if(ch == ' ') *T = NULL;
 32     else
 33     {
 34         *T = (BiThrNode *)malloc(sizeof(BiThrNode));
 35         (*T)->data = ch;
 36         //at start,make the tag linking
 37         (*T)->rTag = LINK;
 38         (*T)->lTag = LINK;
 39         //printf("%c",(*T)->data);
 40         createBiTree(&(*T)->lChild);
 41         createBiTree(&(*T)->rChild);
 42     }
 43     return OK;
 44 }
 45 
 46 //thread the node
 47 void InThreading(BiThrTree t)
 48 {
 49     if(t)
 50     {
 51         InThreading(t->lChild);
 52         printf("%c",t->data);
 53         //the node is thread node when its child is null
 54         if(!t->lChild)
 55         {
 56             t->lTag = THREAD;
 57             t->lChild = pre;
 58         }
 59         if(!t->rChild)
 60         {
 61             pre->rTag = THREAD;
 62             pre->rChild = t;
 63         }
 64         pre = t;
 65         InThreading(t->rChild);
 66     }
 67 }
 68 
 69 Status InOrderThreading(BiThrTree *Thrt,BiThrTree T)
 70 {
 71     //printf("inorder\n");
 72     *Thrt = (BiThrTree)malloc(sizeof(BiThrNode));
 73 
 74     (*Thrt)->lTag = LINK;
 75     (*Thrt)->rTag = THREAD;
 76     //firstly ,the right child points to itself,when finding the last point,it points to the last point
 77     (*Thrt)->rChild = *Thrt;
 78     if(!T)
 79     {
 80         //printf("inorder1\n");
 81         (*Thrt)->lChild = *Thrt;
 82     }
 83     else
 84     {
 85         //printf("inorder2\n");
 86         (*Thrt)->lChild = T;
 87         pre = *Thrt;
 88 
 89         InThreading(T);
 90 
 91         //last point is threaded
 92         pre->rChild = *Thrt;
 93         pre->rTag = THREAD;
 94         (*Thrt)->rChild = pre;
 95     }
 96 
 97     return OK;
 98 }
 99 
100 int main()
101 {
102     BiThrTree base = NULL,thrdBase = NULL;
103     //create the tree
104     createBiTree(&base);
105     InOrderThreading(&thrdBase,base);
106 
107     return 0;
108 }
代碼以下:
相關文章
相關標籤/搜索