//// 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;
}
数据结构--二叉树(线索链表)
最新推荐文章于 2022-11-19 17:53:05 发布