本文實例講述了C語言實現線索二叉樹的定義與遍歷。分享給大家供大家參考,具體如下:
#include <stdio.h>#include <malloc.h>typedef char TElemType;// 二叉樹的二叉線索存儲表示typedef enum{ Link, Thread}PointerTag; // Link(0):指針,Thread(1):線索typedef struct BiThrNode{ TElemType data; struct BiThrNode *lchild,*rchild; // 左右孩子指針 PointerTag LTag,RTag; // 左右標志}BiThrNode,*BiThrTree;TElemType Nil = ' '; // 字符型以空格符為空BiThrTree pre; // 全局變量,始終指向剛剛訪問過的結點// 按先序輸入二叉線索樹中結點的值,構造二叉線索樹T// 空格(字符型)表示空結點int CreateBiThrTree(BiThrTree *T){ TElemType h; scanf("%c",&h); if(h==Nil) *T=NULL; else { *T=(BiThrTree)malloc(sizeof(BiThrNode)); if(!*T) exit(0); (*T)->data=h; // 生成根結點(先序) CreateBiThrTree(&(*T)->lchild); // 遞歸構造左子樹 if((*T)->lchild) // 有左孩子 (*T)->LTag=Link; CreateBiThrTree(&(*T)->rchild); // 遞歸構造右子樹 if((*T)->rchild) // 有右孩子 (*T)->RTag=Link; } return 1;}// 算法6.7 P135// 中序遍歷進行中序線索化。void InThreading(BiThrTree p){ 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); // 遞歸右子樹線索化 }}// 算法6.6 P134// 中序遍歷二叉樹T,并將其中序線索化,Thrt指向頭結點。int InOrderThreading(BiThrTree *Thrt,BiThrTree T){ *Thrt=(BiThrTree)malloc(sizeof(BiThrNode)); // 建頭結點 if(!*Thrt) exit(0); (*Thrt)->LTag=Link; //標志左孩子為指針 (*Thrt)->RTag=Thread; //標志右孩子為線索 (*Thrt)->rchild=*Thrt; // 右指針回指 if(!T) // 若二叉樹空,則左指針回指 (*Thrt)->lchild=*Thrt; else { (*Thrt)->lchild=T; //頭結點左指針指向樹的根 pre = *Thrt; InThreading(T); // 中序遍歷進行中序線索化 pre->RTag=Thread; // 最后一個結點線索化 pre->rchild=*Thrt; (*Thrt)->rchild=pre; } return 1;}// 算法6.5 P134// 中序遍歷二叉線索樹T(頭結點)的非遞歸算法。int InOrderTraverse_Thr(BiThrTree T,int(*Visit)(TElemType)){ BiThrTree p; p=T->lchild; // p指向根結點 while(p!=T) { // 空樹或遍歷結束時,p==T while(p->LTag==Link) p=p->lchild; if(!Visit(p->data)) // 訪問其左子樹為空的結點 return 0; while(p->RTag==Thread&&p->rchild!=T) { p=p->rchild; Visit(p->data); // 訪問后繼結點 } p=p->rchild; } return 1;}int vi(TElemType c){ printf("%c ",c); return 1;}int main(){ BiThrTree H,T; printf("請按先序輸入二叉樹(如:ab三個空格,表示a為根結點," "b為左子樹的二叉樹)/n"); CreateBiThrTree(&T); // 按先序產生二叉樹 InOrderThreading(&H,T); // 中序遍歷,并中序線索化二叉樹 printf("中序遍歷(輸出)二叉線索樹:/n"); InOrderTraverse_Thr(H,vi); // 中序遍歷(輸出)二叉線索樹 printf("/n"); system("pause"); return 0;}
運行結果:
希望本文所述對大家C語言程序設計有所幫助。
新聞熱點
疑難解答
圖片精選