数据结构线索二叉树的构造及其中序遍历代码

#include<iostream>
using namespace std;
typedef char TElemType;
typedef struct BiThrNode
{
	TElemType data;
	struct 	BiThrNode *lchild,*rchild;
	int ltag,rtag;
}BiThrNode,*BiThrTree;
BiThrTree pre;
void bianli(BiThrTree t)
{
	if(t!=NULL)
	{
		
		bianli(t->lchild);
		cout<<t->data<<t->ltag<<t->rtag<<endl;
		bianli(t->rchild);
	}
}
void InThreading(BiThrTree p)//以结点P为根的子树中序线索化; 
{
	if(p)
	{
		InThreading(p->lchild);//左子树递归线索化 
		if(!p->lchild)
		{
			p->ltag=1;
			p->lchild=pre;
		}
		else 
			p->ltag=0;
		if(!pre->rchild)
		{
			pre->rtag=1;
			pre->rchild=p;
		}
		else 
			pre->rtag=0;
		pre=p;
		InThreading(p->rchild);//右子树递归线索化 
		//交换以上代码顺序可实现先序,后序线索化 
		
	}
}

void InOrderThreading(BiThrTree &Thrt,BiThrTree t)//带头结点的二叉树中序线索化 
{
	Thrt=new BiThrNode;//建立头结点 
	Thrt->ltag=0;//头结点有左孩子,若树非空,则左孩子为树根 
	Thrt->rtag=1;//头结点的右孩子设置为线索 
	Thrt->rchild=Thrt;//初始化有指针指向自己 
	if(!t)//树空 
	{
		Thrt->lchild=Thrt;
	} 
	else
	{
		Thrt->lchild=t;//头结点指向树根 
		pre=Thrt;//pre指向头结点
		 
		InThreading(t);
		pre->rchild=Thrt;//线索化后pre指向最右节点,pre右结点指向头结点 
		pre->rtag=1;
		Thrt->rchild=pre;
	}
	
}
void InOrderTraverse_Thr(BiThrTree t)
{
	BiThrTree p=t->lchild;
	while(p!=t)
	{
		while(p->ltag==0)
			p=p->lchild;
		cout<<p->data;
		while(p->rtag==1&&p->rchild!=t)
		{
			p=p->rchild;
			cout<<p->data;
		}
		p=p->rchild;
	}
}
void creattree(BiThrTree &t)
{
	TElemType ch;
	cin>>ch;
	if(ch=='#')
	{
		t=NULL;
	}
	else
	{
		t=new BiThrNode;
		t->data=ch;
		t->ltag=0;
		t->rtag=0;
		creattree(t->lchild);
		creattree(t->rchild);
	}
}
int main()
{
	BiThrTree t;
	BiThrTree Thrt;
	cout<<"请输入树的先序序列:"<<endl;
	creattree(t);
	InOrderThreading(Thrt,t);
	cout<<"中序线索二叉树遍历为:"<<endl; 
	InOrderTraverse_Thr(Thrt);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值