数据结构--树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;
}
相关推荐
点云SLAM15 分钟前
C++ 中的栈(Stack)数据结构与堆的区别与内存布局(Stack vs Heap)
开发语言·数据结构·c++·内存布局·栈数据结构·c++标准算法·heap内存分配
前端小L1 小时前
图论专题(六):“隐式图”的登场!DFS/BFS 攻克「岛屿数量」
数据结构·算法·深度优先·图论·宽度优先
-大头.1 小时前
Python数据结构之旅:09-图论基础——连接万物的网络
数据结构·图论
zz0723201 小时前
数据结构 —— 队列
数据结构
Bear on Toilet2 小时前
C++_Bug:现代写法拷贝构造中 swap 写法之小坑
数据结构·c++·bug
潼心1412o2 小时前
数据结构(长期更新)第8讲:队列
数据结构
fashion 道格3 小时前
C 语言希尔排序:原理、实现与性能深度解析
数据结构·算法·排序算法
如意猴3 小时前
实现链式结构二叉树--递归中的暴力美学(第13讲)
数据结构
初夏睡觉3 小时前
P1048 [NOIP 2005 普及组] 采药
数据结构·c++·算法
Zero不爱吃饭5 小时前
环形链表(C)
数据结构·链表