1. 程式人生 > >線索二叉樹的完整程式碼實現

線索二叉樹的完整程式碼實現

線索二叉樹的完整程式碼,可直接執行
程式碼如下:

//線索二叉樹
#include<stdlib.h>
#include<stdio.h>

typedef char TElemType;

typedef enum {Link,Thread} PointerTag;

typedef  struct BiThrNode
{
    TElemType data;
    struct BiThrNode *lchild,*rchild;
    PointerTag LTag;
    PointerTag RTag;
}BiThrNode, *BiThrTree;

BiThrTree pre=
NULL; //中序遍歷線索化的遞迴函式 void InThreading(BiThrTree p) { if(p) { InThreading(p->lchild); printf("%c",p->data); if(!p->lchild) { p->LTag=Thread; p->lchild=pre; } if(!p->rchild) { pre->
RTag=Thread; pre->rchild=p; } pre=p; InThreading(p->rchild); } } //建立頭指標,使其左指標指向根結點,右指標指向遍歷的最後一個結點 void InOrder_Thr(BiThrTree *Thr,BiThrTree T) { *Thr=(BiThrTree)malloc(sizeof(BiThrNode)); (*Thr)->LTag=Link; (*Thr)->RTag=Thread; (*Thr)->
rchild=*Thr; if(!T) (*Thr)->lchild=*Thr; else { (*Thr)->lchild=T; pre=*Thr; InThreading(T); pre->RTag=Thread; pre->rchild=*Thr; (*Thr)->rchild=pre; } } //按前序輸入二叉樹 void CreateBiTree(BiThrTree *T) { TElemType ch; scanf("%c",&ch); if(ch=='#') *T=NULL; else { *T=(BiThrTree)malloc(sizeof(BiThrNode)); (*T)->data=ch; CreateBiTree(&(*T)->lchild); CreateBiTree(&(*T)->rchild); } } void main() { BiThrTree T,Thr=NULL; printf("請輸入你想建立的二叉樹"); CreateBiTree(&T); InOrder_Thr(&T,T); }

以上是最基本的程式碼,是看《大話資料結構》時根據書上程式碼編寫的,適合最最基礎的人看,有問題可以評論,同是菜鳥,我們一起討論嘛~