数据结构--树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;
}
相关推荐
wadesir3 分钟前
掌握Rust并发数据结构(从零开始构建线程安全的多线程应用)
数据结构·安全·rust
charliejohn1 小时前
计算机考研 408 数据结构 哈夫曼
数据结构·考研·算法
好易学·数据结构2 小时前
可视化图解算法76:最大子数组和
数据结构·算法·leetcode·面试·动态规划·力扣·笔试
falldeep3 小时前
Pandas入门指南
数据结构·算法·leetcode·pandas
闲看云起4 小时前
Leetcode-day4:从「移动零」到「盛最多水的容器」
数据结构·算法·leetcode·职场和发展
nuowenyadelunwen4 小时前
Harvard CS50 Problems Set 5
数据结构·harvard cs50·树,哈希表,链表
mjhcsp5 小时前
P14795 [JOI 2026 二次预选] 分班 / Class Division
数据结构·c++·算法
girl-07265 小时前
2025.12.29实验题目分析总结
数据结构·算法
sin_hielo5 小时前
leetcode 840
数据结构·算法·leetcode
吴声子夜歌6 小时前
数据结构——通用树(N叉树)
数据结构