线索二叉树

线索二叉树的作用:
(1)将各结点的空指针利用起来;
(2)左分支指向其前驱结点,右分支指向其后驱结点;

线索二叉树的代码编写如下:

1.创建树节点结构,线索二叉树相对于普通的二叉树结点,多了两个标志位lTag和rTag;lTag=1时表明左指针为线索指针,lTag=0时表明左指针为左孩子指针;rTag=1时表明右指针为线索指针,rTag=0时表明左指针为右孩子指针;

//创建线索树结点
typedef struct BiThrNode
{
	char data;
	BiThrNode *lchild, *rchild;
	PointerTag lTag;
	PointerTag rTag;
}BiThrNode,*BiThrTree;
//创建全局变量,指向刚刚访问过的结点
BiThrTree pre;
  1. 采用前序遍历创建树结构
//创建二叉树,用户遵循前序遍历的规则输入数据
void CreateBiTree(BiThrTree *T)//这里采用指针的方法进行传入,是为了保证函数中创建的树结构即为主函数中的树结构
{
	char c;
	scanf_s("%c", &c);
	if (c == ' ')
		*T = NULL;
	else
	{
		*T = (BiThrNode*)malloc(sizeof(BiThrNode));
		(*T)->data = c;
		(*T)->lTag = Link;
		(*T)->rTag = Link;
		CreateBiTree(&(*T)->lchild);
		CreateBiTree(&(*T)->rchild);
	}
}
  1. 通过增加头结点的方式来创建线索二叉树
//通过中序遍历将创建的二叉树变为线索二叉树,需要增加头结点的方式
void inThreading(BiThrTree T)
{
	if (T)
	{
		inThreading( T->lchild);//左子树线索化
		if (!T->lchild)
		{
			T->lTag = Thread;
			T->lchild = pre;
		}
		else
			T->lTag = Link;
		if (!pre->rchild)
		{
			pre->rTag = Thread;
			pre->rchild = T;
		}
		else
			pre->rTag = Link;
		pre = T;
		inThreading(T->rchild);//右子树线索化
	}
}
  1. 采用非递归的方式输出中序线索二叉树的各结点
//使用非递归的方式(利用线索二叉树的前驱和后继的性质)将树结构以中序遍历顺序输出
void InOrderTraversePrint(BiThrNode * p)//p为头结点
{
	BiThrNode *T = p->lchild;//T指向根节点
	while (T != p)
	{
		while (T->lTag==Link)
		{
			T = T->lchild;
		}
		visit(T->data);
		while (T->rTag==Thread && T->rchild != p)
		{
			T = T->rchild;
			visit(T->data);
		}
		T = T->rchild;
	}
}

5.上述主函数如下

int main()
{
	BiThrTree P, T = NULL;
	CreateBiTree(&T);
	InOrderThreading(&P, T);
	cout << "中序遍历输出结果为: " << endl;
	InOrderTraversePrint(P);
	cout << endl;
	system("pause");
	return 0;
}
}```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值