数据结构-C语言版-二叉树中序线索化

 二叉树中的线索化问题,数据结构最核心、密集的考点之一:树,以中序二叉树的线索化

代码参考王道数据结构课程!

#include<stdio.h>
#include<stdlib.h>
//创建链二叉数结构,并设置两个标志位tag用来表示
//左孩子和有孩子是否线索化
typedef struct BiNode {
	char data;
	struct BiNode* lchild, * rchild;
	int ltag, rtag;
}*Bitree;
BiNode* pre = NULL;
void Initialtree(Bitree* t)
{//初始化
	*t = NULL;
}
void  Creattree(Bitree *t)
{
	//传统的递归建立链树的过程
	char c;
	scanf_s("%c", &c);
	if (c=='#')
	{
		*t = NULL;
	}
	else {
		*t = (Bitree)malloc(sizeof(BiNode));
		(*t)->data = c;
		 Creattree(&(*t));
		 Creattree(&(*t));
	}
}
void visit(Bitree t)
{
	//访问B树,当该节点的左孩子为空时,
	//代表有空的链域出现,此时将这个空链域线索化
	if (t->lchild == NULL)
	{
		t->lchild = pre;
		t->ltag = 1;
	}
	//当pre指针指向的不是最后一个节点并且没有右孩子时
	//让右空链域线索化
	if (pre != NULL && pre->rchild==NULL)
	{
		pre->rchild = t;
		pre->rtag = 1;
	}
	//让pre指向下一个遍历的节点
	pre = t;
}
void thread(Bitree t)
{
	//中序遍历,左中右的顺序
	if (t != NULL)
	{
		thread(t->lchild);
		visit(t);
		thread(t->rchild);
	}
}

void   Creathread(Bitree t)
{
	//线索化主函数,让指针pre按照中序遍历进行扫描顺便线索化
	pre = NULL;
	if (t != NULL)
	{
		thread(t);
		if (pre->rchild == NULL)
			pre->rtag = 1;
	}
}
int main()
{
	//主函数,很简单,不解释了
	printf("请输入需要存放进二叉树的数据,以#结尾!\n");
	 Bitree t;
	 Initialtree(&t);
	 Creattree(&t);
	 Creathread(t);
	 getchar();
	//
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值