线索二叉树的建立和中序遍历

#include<iostream>
using namespace std;

typedef char Elemtype;
typedef enum{LINK=0,THREAD=1}linktype;

typedef struct BiThNode
{
	Elemtype data;
	BiThNode *leftchild;
	BiThNode *rightchild;
    linktype ltag;
	linktype rtag;
}BiThNode;

BiThNode *BuyNode()
{
	BiThNode *ptr = new BiThNode;
	if(ptr == NULL) return NULL;
    memset(ptr,0,sizeof(BiThNode));
	return ptr;
}
void freeNode(BiThNode *p)
{
	delete p;
}
//建树
BiThNode *builttree(Elemtype *&ptr)
{
	BiThNode *s = NULL;
	while(ptr != NULL && *ptr != '#')
	{
         s = BuyNode();
		 s->data = *ptr;
		 s->leftchild = builttree(++ptr);
		 s->rightchild = builttree(++ptr);
	}
	return s;
}
//中序遍历
void Miinoder(BiThNode *p)
{
	if(p != NULL)
	{
        Miinoder(p->leftchild);
		cout<<p->data<<" ";
		Miinoder(p->rightchild);
	}

}

//用递归线索话一颗二叉树
//1.传参的
void Thread(BiThNode *p, BiThNode *&ptr)
{
	if(p != NULL)
	{
		Thread(p->leftchild,ptr);
		
		if(p->leftchild == NULL)
		{ 
			p->ltag = THREAD;
			p->leftchild = ptr;
		}
		if(ptr != NULL && ptr->rightchild == NULL)
		{
			ptr->rightchild = p;
			ptr->rtag = THREAD;
		}
		ptr = p;
		
		Thread(p->rightchild,ptr);
		
	} 
	
}
 void MakeThread(BiThNode *p)
 {
	 if(p == NULL) return ;
	 BiThNode *ptr = NULL;
	 Thread(p,ptr);
	 ptr->rtag = THREAD;
	 ptr->rightchild = NULL;
 }
 //2.有个全局变量
 BiThNode *ptr = NULL;
 void MakeThread1(BiThNode *p)
 {
	 if(p != NULL)
	 {
		 MakeThread1(p->leftchild);

		 if(p->leftchild == NULL)
		 { 
			 p->ltag = THREAD;
			 p->leftchild = ptr;
		 }
		 if(ptr != NULL && ptr->rightchild == NULL)
		 {
			 ptr->rightchild = p;
			 ptr->rtag = THREAD;
		 }
		 ptr = p;

		 MakeThread1(p->rightchild);

	 } 

 }
 /*
 main()中是这样是{ ptr->rtag = THREAD;
 ptr->rightchild = NULL;}
 */
 
//中序遍历一颗线索二叉树

BiThNode *First(BiThNode *p)
{
	while(p != NULL && p->ltag != THREAD)
	{
		p = p->leftchild; 
	}
	return p;
}
BiThNode *Next(BiThNode *p)
{
	if(p == NULL) return NULL;
	if(p->rtag == LINK)
	{
		BiThNode *ptr = First(p->rightchild);
		return ptr;
	}
	else
	{
		return p->rightchild;
	}
}
void ThreadMiinder(BiThNode *p)
{
	for(BiThNode *s = First(p);s != NULL;s = Next(s))
	{
		cout<<s->data<<" ";
	}
	cout<<endl;
}

int main()
{
	char *str = "ABC##DE##F##G#H##";
	BiThNode *root = NULL;
	BiThNode *ptr = NULL;
    root = builttree(str);
	
	
	MakeThread(root);
  
    
	ThreadMiinder(root);
	/*Miinoder(root);
	cout<<endl;*/
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值