数据结构--树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;
}
相关推荐
小字节,大梦想19 分钟前
【C++】二叉搜索树
数据结构·c++
我是哈哈hh40 分钟前
专题十_穷举vs暴搜vs深搜vs回溯vs剪枝_二叉树的深度优先搜索_算法专题详细总结
服务器·数据结构·c++·算法·机器学习·深度优先·剪枝
丶Darling.1 小时前
LeetCode Hot100 | Day1 | 二叉树:二叉树的直径
数据结构·c++·学习·算法·leetcode·二叉树
labuladuo5201 小时前
Codeforces Round 977 (Div. 2) C2 Adjust The Presentation (Hard Version)(思维,set)
数据结构·c++·算法
Indigo_code2 小时前
【数据结构】【链表代码】合并有序链表
数据结构·windows·链表
jiyisuifeng19912 小时前
代码随想录训练营第54天|单调栈+双指针
数据结构·算法
我言秋日胜春朝★2 小时前
【C++】红黑树
数据结构
新晓·故知2 小时前
<基于递归实现线索二叉树的构造及遍历算法探讨>
数据结构·经验分享·笔记·算法·链表
gorgor在码农3 小时前
Mysql 索引底层数据结构和算法
数据结构·数据库·mysql
武昌库里写JAVA4 小时前
【Java】Java面试题笔试
c语言·开发语言·数据结构·算法·二维数组