#include<iostream>
#include<stdlib.h>
using namespace std;
typedef char TElemType;
typedef enum { Link, Thread } PointerTag; //enum{}枚举类型
//线索二叉树
//存储结构
typedef struct BiThrNode
{
TElemType data;
struct BiThrNode *lchlid, *rchild;
PointerTag LTag;
PointerTag RTag;
}BiThrNode, *BiThrTree;
//创建二叉树
//前序
void CreateBiTree(BiThrTree *T)
{
TElemType ch;
cin >> ch;
if (ch == '#')
{
*T = NULL;
}
else
{
*T = (BiThrTree)malloc(sizeof(BiThrNode));
(*T)->data = ch;
CreateBiTree(&(*T)->lchlid);
CreateBiTree(&(*T)->rchild);
}
}
//中序线索化
BiThrTree pre = NULL;//全局变量 始终指向刚刚访问过的节点
void InThreading(BiThrTree p)
{
if (p)
{
InThreading(p->lchlid);
if (!p->lchlid)
{
p->LTag = Thread;
p->lchlid = pre; //指向前驱
}
if (pre != NULL && !pre->rchild)
{
pre->RTag = Thread;
pre->rchild = p;//指向后继
}
pre = p;
InThreading(p->rchild);
}
}
//线索二叉树的遍历
//中序遍历
void InOrderTraverse_Thr(BiThrTree T)
{
BiThrTree p;
p = T->lchlid;
while (p&&p != T)
{
while (p->LTag == Link)
{
p = p->lchlid;
}
if (p) {
cout << p->data;
}
while (p&&p->LTag == Thread && T->rchild != T)
{
p = p->rchild;
if (p) {
cout << p->data;
}//访问中序线索二叉树的右节点(有线索标志的)的后继结点
}
if (p) {
p = p->rchild;
}
}
}
int main()
{
BiThrTree t;
CreateBiTree(&t);
InThreading(t);
InOrderTraverse_Thr(t);
}
数据结构那点事--线索二叉树
最新推荐文章于 2024-09-04 14:03:13 发布