資料結構--二叉樹(線索連結串列)
阿新 • • 發佈:2019-02-07
//// Threaded Binary Tree.cpp : Defines the entry point for the console application. /*-----CODE FOR FUN--------------- -------CREATED BY Dream_Whui------ -------2015-2-6-------------------*/ #include "stdafx.h" #include <iostream> #include <stack> using namespace std; #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define INFEASIBLE -1 #define TelemType char typedef enum PointerTag { Link, Thread }; typedef struct BiThrNode//定義線索連結串列的結構 { TelemType data;//結點元素值 struct BiThrNode *lchild, *rchild;//左子樹,右子樹 PointerTag LTag, RTag;//LTag=0,lchild表示左孩子,LTag=1.lchild表示直接前驅;同理得RTag和rchild }BiThrNode, *BiThrTree; int CreateBiThrTree(BiThrTree &T)//按先序建立樹 { char ch; cin>>ch; if(ch=='#') T=NULL; else { T = (BiThrTree)malloc(sizeof(BiThrTree)); T->data = ch; CreateBiThrTree(T->lchild); CreateBiThrTree(T->rchild); } return OK; } void InThreading(BiThrTree p, BiThrTree &pre) { if(p) { InThreading(p->lchild,pre);//左子樹線索化 if(!p->lchild)//前驅線索 { p->LTag = Thread; p->lchild = pre; } else p->LTag = Link; if(!pre->rchild)//後繼線索 { pre->RTag = Thread; pre->rchild = p; } pre = p; pre->RTag = Link; InThreading(p->rchild,pre);//右子樹線索化 } } int InOrderThreading(BiThrTree &Thrt, BiThrTree T)//中序遍歷二叉樹,並將其中序線索化 { BiThrTree pre; Thrt = (BiThrTree)malloc(sizeof(BiThrTree));//建立頭結點 if(!Thrt) return ERROR; Thrt->LTag = Link; Thrt->RTag = Thread; Thrt->rchild = Thrt; if(!T) Thrt->lchild = Thrt; else { pre = Thrt; Thrt->lchild = T; InThreading(T,pre); pre->RTag = Thread;//最後一個結點線索化 pre->rchild = Thrt; Thrt->rchild = pre; } return OK; } void Visit(TelemType e) { cout<<e<<" "; } int InOrderTraverse_Thr(BiThrTree T, void(*Visit)(TelemType))//線索化訪問 { BiThrTree 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; } return OK; } int main(int argc, char* argv[]) { BiThrTree f = NULL; CreateBiThrTree(f); BiThrTree P; InOrderThreading(P,f); InOrderTraverse_Thr(P,Visit); cout<<"................"<<endl; return 0; }