線索二叉樹的構建和遍歷------小甲魚數據結構和算法
阿新 • • 發佈:2017-07-26
-- tag typedef pre == 約定 cnblogs amp scan
#include <stdio.h> #include <stdlib.h> typedef char ElemType; // 線索存儲標誌位 // Link(0):表示指向左右孩子的指針 // Thread(1):表示指向前驅後繼的線索 typedef enum {Link, Thread} PointerTag; typedef struct BiThrNode { char data; struct BiThrNode *lchild,*rchild; PointerTag ltag; PointerTag rtag; } BiThrNode,*BiThrTree; // 定義一個全局變量表示剛剛走過的節點 BiThrTree pre; // 創建一棵二叉樹,約定用戶遵照前序遍歷的方式輸入數據 void CreateBiThrTree(BiThrTree *T) { char c; scanf("%c",&c); if ( ‘ ‘ == c ){ *T = NULL; }else { *T = (BiThrNode *)malloc(sizeof(BiThrNode)); (*T)->data = c; (*T)->ltag = Link; (*T)->rtag = Link; CreateBiThrTree(&(*T)->lchild); CreateBiThrTree(&(*T)->rchild); } } // 中序遍歷線索化 void InThreading(BiThrTree T){ if ( T ) { InThreading(T->lchild); // 遞歸左孩子線索化 if( !T->lchild ){ T->ltag = Thread; T->lchild = pre; } if ( !pre->rchild ){ pre->rtag = Thread; pre->rchild = T; } pre = T; InThreading(T->rchild); // 遞歸右孩子線索化 } } // 初始化一個頭指針 void InOrderThreading( BiThrTree *p, BiThrTree T){ *p = (BiThrNode *)malloc(sizeof(BiThrNode)); (*p)->ltag = Link; (*p)->rtag = Link; (*p)->rchild = *p; if (!T) { (*p)->lchild = *p; }else { (*p)->lchild = T; pre = *p; InThreading(T); pre->rchild = *p; pre->rtag = Thread; (*p)->rchild = pre; } } void visit (char c){ printf("%c",c); } // 中序遍歷二叉樹,叠代 void InOrderTraverse( BiThrTree T ) { BiThrTree p; p = T->lchild; while( p!=T ){ while( p->ltag == Link ){ p = p->lchild; } visit(p->data); while( p->rtag == Thread && p->rchild !=T ){ p = p->rchild; visit(p->data); } p = p->rchild; } } int main() { BiThrTree P,T = NULL; CreateBiThrTree( &T ); InOrderThreading( &P, T ); printf("中序遍歷二叉樹的結果為:"); InOrderTraverse( P ); printf("\n"); return 0; }
運行截圖
線索二叉樹的構建和遍歷------小甲魚數據結構和算法