数据结构中线索二叉树的基本操作

带头结点的线索二叉树(如图),头结点的lchild指针指向二叉树的根结点(A),rchild指针指向中序遍历时访问的最后一个结点(G)。

源码:

#include <stdio.h> 
#include <stdlib.h>

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2

typedef enum{Link,Thread}PointerTag;
//Link==0,Tag=Link表示指针指向孩子,Thread==1,Tag=Thread表示指针指向前驱后继 
typedef char TElemtype;
typedef int Status;

typedef struct BiThrNode{
	TElemtype data;
	struct BiThrNode *lchild, *rchild;
	PointerTag LTag,RTag;
}BiThrNode, *BiThrTree;
//以前序遍历的方式构建线索二叉树 
Status Create_BiThrTree(BiThrTree *T)
{
	TElemtype e;
	scanf("%c",&e);
	if(e=='#')
		*T=NULL;
	else
	{
		*T=(BiThrTree)malloc(sizeof(BiThrNode));
		if(!*T)
			return OVERFLOW;
		(*T)->data=e;
		Create_BiThrTree(&(*T)->lchild);
		if((*T)->lchild)
			(*T)->LTag=Link;
		else
			(*T)->LTag=Thread;
		Create_BiThrTree(&(*T)->rchild);
		if((*T)->rchild)
			(*T)->RTag=Link;
		else
			(*T)->RTag=Thread;
	}
	return OK; 
}

BiThrTree pre=NULL;	//全局变量,始终指向刚刚访问过的结点 
//以中序遍历的方式线索化 
Status InThreading(BiThrTree p)
{
	if(p)
	{
		InThreading(p->lchild);
		if(!p->lchild)	//没有左孩子 
		{
			p->LTag=Thread;
			p->lchild=pre;	
		}
		if(!pre->rchild)
		{
			pre->RTag=Thread;
			pre->rchild=p;
		}
		pre=p;
		InThreading(p->rchild);
	}
	return OK;
}
//以中序遍历的方式线索化 (带头结点) 
Status InOrderThreading_Thrt(BiThrTree *Thrt,BiThrTree T)
{
	*Thrt=(BiThrTree)malloc(sizeof(BiThrNode));
	if(!*Thrt)
		exit(OVERFLOW);
	(*Thrt)->data=NULL;
	(*Thrt)->LTag=Link;
	(*Thrt)->RTag=Thread;
	(*Thrt)->rchild=*Thrt;
	if(!T)
		(*Thrt)->lchild=*Thrt;
	else
	{
		(*Thrt)->lchild=T;
		pre=*Thrt;
		InThreading(T);
		pre->RTag=Thread;
		pre->rchild=*Thrt;
		(*Thrt)->rchild=pre;
	}
	return OK;
}
//以中序遍历的顺序输出带头结点的线索二叉树 (非递归) 
Status InOrderTraverse_Thrt(BiThrTree Thrt)
{
	BiThrTree p=Thrt->lchild;
	while(p!=Thrt)
	{
		while(p->LTag==Link)
			p=p->lchild;
		printf("%c",p->data);
		while(p->RTag==Thread && p->rchild!=Thrt)
		{
			p=p->rchild;
			printf("%c",p->data);
		}
		p=p->rchild;
	}
	printf("\n"); 
	return OK;
}

int main()
{  
	BiThrTree T,H;
 	printf("请按前序输入二叉树 (如:'ABDH##I##EJ###CF##G##')\n");
 	Create_BiThrTree(&T); 		/*  按前序产生二叉树 */ 
	InOrderThreading_Thrt(&H,T); /*  中序遍历,并中序线索化二叉树 */
	printf("中序遍历(输出)二叉线索树:\n"); 
	InOrderTraverse_Thrt(H); 	/*  中序遍历(输出)二叉线索树 */
	return 0;
}

以前序遍历的顺序输入以下图中的二叉树

输出结果:


猜你喜欢

转载自blog.csdn.net/weixin_40908734/article/details/79314439