/* c6-3.h 二叉樹的二叉線索存儲表示 */ typedef enum{Link,Thread}PointerTag; /* Link(0):指針,Thread(1):線索 */ typedef struct BiThrNode { TElemType data; struct BiThrNode *lchild,*rchild; /* 左右孩子指針 */ PointerTag LTag,RTag; /* 左右標誌 */ }BiThrNode,*BiThrTree;
/* bo6-3.c 二叉樹的二叉線索存儲(存儲結構由c6-3.h定義)的基本操做 */ Status CreateBiThrTree(BiThrTree *T) { /* 按先序輸入二叉線索樹中結點的值,構造二叉線索樹T */ /* 0(整型)/空格(字符型)表示空結點 */ TElemType h; #if CHAR scanf("%c",&h); #else scanf("%d",&h); #endif if(h==Nil) *T=NULL; else { *T=(BiThrTree)malloc(sizeof(BiThrNode)); if(!*T) exit(OVERFLOW); (*T)->data=h; /* 生成根結點(先序) */ CreateBiThrTree(&(*T)->lchild); /* 遞歸構造左子樹 */ if((*T)->lchild) /* 有左孩子 */ (*T)->LTag=Link; CreateBiThrTree(&(*T)->rchild); /* 遞歸構造右子樹 */ if((*T)->rchild) /* 有右孩子 */ (*T)->RTag=Link; } return OK; } BiThrTree pre; /* 全局變量,始終指向剛剛訪問過的結點 */ void InThreading(BiThrTree p) { /* 中序遍歷進行中序線索化。算法6.7 */ if(p) { InThreading(p->lchild); /* 遞歸左子樹線索化 */ if(!p->lchild) /* 沒有左孩子 */ { p->LTag=Thread; /* 前驅線索 */ p->lchild=pre; /* 左孩子指針指向前驅 */ } if(!pre->rchild) /* 前驅沒有右孩子 */ { pre->RTag=Thread; /* 後繼線索 */ pre->rchild=p; /* 前驅右孩子指針指向後繼(當前結點p) */ } pre=p; /* 保持pre指向p的前驅 */ InThreading(p->rchild); /* 遞歸右子樹線索化 */ } } Status InOrderThreading(BiThrTree *Thrt,BiThrTree T) { /* 中序遍歷二叉樹T,並將其中序線索化,Thrt指向頭結點。算法6.6 */ *Thrt=(BiThrTree)malloc(sizeof(BiThrNode)); if(!*Thrt) exit(OVERFLOW); (*Thrt)->LTag=Link; /* 建頭結點 */ (*Thrt)->RTag=Thread; (*Thrt)->rchild=*Thrt; /* 右指針回指 */ if(!T) /* 若二叉樹空,則左指針回指 */ (*Thrt)->lchild=*Thrt; else { (*Thrt)->lchild=T; pre=*Thrt; InThreading(T); /* 中序遍歷進行中序線索化 */ pre->rchild=*Thrt; pre->RTag=Thread; /* 最後一個結點線索化 */ (*Thrt)->rchild=pre; } return OK; } Status InOrderTraverse_Thr(BiThrTree T,Status(*Visit)(TElemType)) { /* 中序遍歷二叉線索樹T(頭結點)的非遞歸算法。算法6.5 */ BiThrTree p; p=T->lchild; /* p指向根結點 */ while(p!=T) { /* 空樹或遍歷結束時,p==T */ while(p->LTag==Link) p=p->lchild; if(!Visit(p->data)) /* 訪問其左子樹爲空的結點 */ return ERROR; while(p->RTag==Thread&&p->rchild!=T) { p=p->rchild; Visit(p->data); /* 訪問後繼結點 */ } p=p->rchild; } return OK; }
/* main6-3.c 檢驗bo6-3.c的主程序 */ #define CHAR 1 /* 字符型 */ /*#define CHAR 0 /* 整型(兩者選一) */ #if CHAR typedef char TElemType; TElemType Nil=' '; /* 字符型以空格符爲空 */ #else typedef int TElemType; TElemType Nil=0; /* 整型以0爲空 */ #endif #include"c1.h" #include"c6-3.h" #include"bo6-3.c" Status vi(TElemType c) { #if CHAR printf("%c ",c); #else printf("%d ",c); #endif return OK; } void main() { BiThrTree H,T; #if CHAR printf("請按先序輸入二叉樹(如:ab三個空格表示a爲根結點,b爲左子樹的二叉樹)\n"); #else printf("請按先序輸入二叉樹(如:1 2 0 0 0表示1爲根結點,2爲左子樹的二叉樹)\n"); #endif CreateBiThrTree(&T); /* 按先序產生二叉樹 */ InOrderThreading(&H,T); /* 中序遍歷,並中序線索化二叉樹 */ printf("中序遍歷(輸出)二叉線索樹:\n"); InOrderTraverse_Thr(H,vi); /* 中序遍歷(輸出)二叉線索樹 */ printf("\n"); }