1. 程式人生 > >線索二叉樹的C語言實現

線索二叉樹的C語言實現

null 字符 traverse 結點 表示 flow thread 當前 nil

#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "io.h"
#include "math.h"
#include "time.h"

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0

#define MAXSIZE 100 /* 存儲空間初始分配量 */

typedef int Status; /* Status是函數的類型,其值是函數結果狀態代碼,如OK等 */
typedef char TElemType;
typedef enum {Link,Thread} PointerTag; /* Link==0表示指向左右孩子指針, */
/* Thread==1表示指向前驅或後繼的線索 */
typedef struct BiThrNode /* 二叉線索存儲結點結構 */
{
TElemType data; /* 結點數據 */
struct BiThrNode *lchild, *rchild; /* 左右孩子指針 */
PointerTag LTag;
PointerTag RTag; /* 左右標誌 */
} BiThrNode, *BiThrTree;

TElemType Nil=‘#‘; /* 字符型以空格符為空 */

Status visit(TElemType e)
{
printf("%c ",e);
return OK;
}

/* 按前序輸入二叉線索樹中結點的值,構造二叉線索樹T */
/* 0(整型)/空格(字符型)表示空結點 */
Status CreateBiThrTree(BiThrTree *T)
{
TElemType h;
scanf("%c",&h);

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)
{
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); /* 遞歸右子樹線索化 */
}
}

/* 中序遍歷二叉樹T,並將其中序線索化,Thrt指向頭結點 */
Status InOrderThreading(BiThrTree *Thrt,BiThrTree T)
{
*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;
}

/* 中序遍歷二叉線索樹T(頭結點)的非遞歸算法 */
Status InOrderTraverse_Thr(BiThrTree T)
{
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;
}

int main()
{
BiThrTree H,T;
printf("請按前序輸入二叉樹(如:‘ABDH##I##EJ###CF##G##‘)\n");
CreateBiThrTree(&T); /* 按前序產生二叉樹 */
InOrderThreading(&H,T); /* 中序遍歷,並中序線索化二叉樹 */
printf("中序遍歷(輸出)二叉線索樹:\n");
InOrderTraverse_Thr(H); /* 中序遍歷(輸出)二叉線索樹 */
printf("\n");

return 0;
}

線索二叉樹的C語言實現