大话数据结构15 : 线索二叉树
生活随笔
收集整理的這篇文章主要介紹了
大话数据结构15 : 线索二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基礎介紹
線索二叉樹就是當用鏈表組成的二叉樹其在葉節點或者分支中有空指針時,將空指針指向自己的前驅后者后繼
記錄后繼
記錄前驅
線索二叉樹
數據結構
代碼實現
#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; } *BiThrTree;TElemType Nil = '#'; /* 字符型以空格符為空 */Status visit(TElemType e) {printf("%c ", e);return OK;}/* 按前序輸入二叉線索樹中結點的值,構造二叉線索樹T */ /* 0(整型)/空格(字符型)表示空結點 */ Status CreateBiThrTree(BiThrTree* T) {TElemType h;h = 1;if (h == Nil)*T = NULL;else{T = new BiThrTree();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;}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; /* 建頭結點 */ // link == 0(*Thrt)->RTag = Thread; // thread == 1(*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; }總結
以上是生活随笔為你收集整理的大话数据结构15 : 线索二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大话数据结构13:二叉树 数组存储
- 下一篇: 大话数据结构16:图