数据结构--树4.2.3(线索二叉树)

利用中序遍历可以解决二叉树中空出来的内存,以及前驱后继的问题。

|------------|----------|----------|----------|------------|
| lchild | ltag | data | rtag | rchild |

------ltag为0时指向该结点的左孩子,为1时指向该结点的前驱。

------rtag为0时指向该结点的有孩子,为1时指向该结点的后继。

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

typedef char ElemType;
//线索存储标志
//Link(0):表示指向左右孩子的指针
//thread(1):表示指向前驱后继的线索 

typedef enum{Link,Thread} Pointertag;

typedef struct  Bithrnode
{
	char data;
	struct Bithrnode * lchild ,* rchild;
	Pointertag ltag;
	Pointertag rtag;
}Bithrnode,*Bithrtree;
//创建一棵二叉树,约定用户遵照前序遍历的方式输入数据
Bithrtree pre;

CreateBithree(Bithrtree *t)
{
	char c;
	scanf("%c",&c);
	if(' '== c)
	{
		*t =  NULL;
	}
	else
	{
		*t = (Bithrnode*)malloc(sizeof(Bithrnode));
		(*t)->data=c;
		(*t)->ltag = Link;
		(*t)->rtag = Link;
		CreateBithree(&(*t)->lchild);
		CreateBithree(&(*t)->rchild);
	}
 } 
 
 //中序遍历
 Inthreading(Bithrtree t)
 {
 	if(t)
 	{
 		Inthreading(t->lchild);//递归左孩子线索化 
 		if(!t->lchild)
 		{
 			t->ltag = Thread;
 			t->lchild = pre;
		 }
		if(!pre->rchild)
		{
			pre->rtag = Thread;
			pre->rchild = t;
		}
		pre = t;
		Inthreading(t->rchild);//递归右孩子线索化 
	 }
  } 

//中序遍历二叉树,非递归
Inordertraverse(Bithrtree t)
{
	Bithrtree p;
	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;
	}
 } 
int main()
{
	Bithrtree p,t =NULL;
	CreateBithree(&t);
	Inthreading(t);
	printf("中序遍历输出结果为:");
	Inordertraverse(p);
	printf("\n");
	return 0;
}
相关推荐
_殊途1 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
秋说6 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen6 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
risc1234568 小时前
BKD 树(Block KD-Tree)Lucene
java·数据结构·lucene
kk_stoper8 小时前
如何通过API查询实时能源期货价格
java·开发语言·javascript·数据结构·python·能源
秋说8 小时前
【PTA数据结构 | C语言版】字符串插入操作(不限长)
c语言·数据结构·算法
遇见尚硅谷10 小时前
C语言:20250714笔记
c语言·开发语言·数据结构·笔记·算法
恸流失12 小时前
java基础-1 : 运算符
java·开发语言·数据结构
yu20241113 小时前
【【异世界历险之数据结构世界(二叉树)】】
数据结构·算法
白雪公主的后妈18 小时前
C#——数据与变量
数据结构·c#·数据与变量