《大话数据结构》二叉树一节的代码

#include 
#include 
using namespace std;

typedef enum {Link,Thread} PointTre;
typedef char TreDataType;

typedef struct TreNode
{
	TreDataType data;
	struct TreNode *LefChild, *RigChild;
	int lTag, rTag;
}TreNode,*TrePtr;
TrePtr pre = NULL;  //始终指向前一结点

int CreateTre(TrePtr &T)  //中序创建二叉树
{
	TreDataType c;
	cin >> c;
	if (c == '#') T = NULL;
	else
	{
		T = new TreNode;
		T->data = c;
		T->lTag = Link;
		T->rTag = Link;
		CreateTre(T->LefChild);
		CreateTre(T->RigChild);
	}
	return 0;
}

int TreDisplay(TrePtr &T)  //中序输出
{
	if (T)
	{
		TreDisplay(T->LefChild);
		cout << T->data << ' ';
		TreDisplay(T->RigChild);
	}
	return 0;
}

int InTreTraverse(TrePtr &T)   //中序遍历进行中序线索化
{
	extern TrePtr pre;
	if (T)
	{
		InTreTraverse(T->LefChild);
		if (!T->LefChild)
		{
			T->lTag = Thread;
			T->LefChild = pre;
		}
		if((pre != NULL) && (!pre->RigChild))
		{
			pre->rTag = Thread;
			pre->RigChild = T;
		}
		pre = T;
		//cout << pre->data << ' ';
		InTreTraverse(T->RigChild);
	}
	return 0;
}

int InOrederThreading(TrePtr &T, TrePtr &H)  //添加头结点
{
	H = new TreNode;
	H->data = '#';
	H->lTag = Link;
	H->rTag = Thread;
	if(!T) 	H->LefChild = H;
	else
	{
		H->LefChild = T;
		pre = H;
		InTreTraverse(T);
		H->RigChild = pre;
		pre->RigChild = H;
		T = H;
	}
	return 0;
}

int InOrderThreading_traverse(TrePtr &T)  //遍历二叉线索链表
{
	TrePtr p = T->LefChild;
	while (p != T) //判断空表 and 判断是否到链表尾部
	{
		while (p->lTag == Link)
		{
			p = p->LefChild;
		}
		cout << p->data;
		while ((p->rTag == Thread) && (p->RigChild!=T))
		{
			p = p->RigChild;
			cout << p->data;
		}
		cout << "  T:"<data << endl;
		p = p->RigChild;
	}
	return 0;
}

int main()
{
	TrePtr T = NULL;
	TrePtr H = NULL;
	freopen("input.txt", "r", stdin);;
	CreateTre(T);
	TreDisplay(T);
	cout << endl;

	InOrederThreading(T, H);
	//cout << T->data << endl;
	InOrderThreading_traverse(T);
	//InTreTraverse(T);
	cout << endl;
	return 0;
}

 

你可能感兴趣的:(《大话数据结构》二叉树一节的代码)