数据结构》严奶奶版本---树(2)中序二叉树 完整源码

本文详细介绍了中序线索二叉树的实现过程,包括建立二叉树、添加链接、中序遍历线索化及中序遍历的完整源码。通过具体的代码示例,展示了如何使用C++实现中序线索二叉树,为读者提供了深入理解数据结构的机会。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


数据结构》树(2)中序二叉树 完整源码


在这里插入图片描述

//中序线索二叉树

#include <iostream>
#include <windows.h>

using namespace std;

typedef char ElemType;

//定义枚举类型 link 0 tread 1
typedef enum{

	link,
	thread

}pointertag;

//定义树的结构类型
typedef struct mtnode{
	
	ElemType data;
	struct mtnode *lchild;
	struct mtnode *rchild;
	pointertag ltag,rtag;

}MTNode,*MTree;

bool create_mtree(MTree &t);//建树
void add_link(MTree t);//指向后继的节点
void in_threading(MTree t);//指向前驱的节点
bool inorder_threading(MTree &thrt,MTree T);//中序遍历线索化
void inorder_traver(MTree t);//中序遍历

MTree pre;

int main()
{
	MTree t;
	MTree thrt;
	cout<<"中序线索二叉树\n";
	create_mtree(t);
	add_link(t);
	inorder_threading(thrt,t);
	inorder_traver(thrt);
	cout<<endl;

	return 0;
}

bool create_mtree(MTree &t)//建树
{
	ElemType data;
	cin>>data;

	if(data == '#')
		t = NULL;
	else
	{
		t = new MTNode;
		if(!t)
			return false;
		
		t->data = data;
		create_mtree(t->lchild);
		create_mtree(t->rchild);
	}

	return true;
}
void add_link(MTree t)
{
	if(t)
	{
		if(t->lchild)
			t->ltag = link;
		if(t->rchild)
			t->rtag = link;
		
		add_link(t->lchild);
		add_link(t->rchild);
	}
}
void in_threading(MTree t)
{
	if(t)
	{
		in_threading(t->lchild);
		if(!t->lchild)
		{
			t->ltag = thread;
			t->lchild = pre;
		}

		if(!pre->rchild)
		{
			pre->rtag = thread;
			pre->rchild = t;
		}

		pre = t;
		in_threading(t->rchild);
	}
}
bool inorder_threading(MTree &thrt,MTree t)
{
	thrt = new MTNode;
	if(!thrt)
		return false;

	thrt->ltag = link;
	thrt->rtag = thread;
	thrt->rchild = thrt;

	if(!t)
		thrt->lchild = thrt;
	else
	{
		thrt->lchild = t;
		pre = thrt;
		in_threading(t);

		pre->rchild = thrt;
		pre->rtag = thread;
		thrt->rchild = pre;
	}

	return true;
}
void inorder_traver(MTree t)
{
	MTree p = t->lchild;
	while(p != t)
	{
		while(p->ltag == link)
			p = p->lchild;
			cout<<p->data<<" ";
			while(p->rtag == thread && p->rchild != t)
			{
				p = p->rchild;
				cout<<p->data<<" ";
			}
		
			p = p->rchild;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值