线索二叉树

利用线索二叉树实现中序遍历

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
//构建线索化二叉树,用其进行中序遍历及中序逆遍历
typedef char elemType;

typedef enum thread
{
	LINK=1,THLINK
}THREAD;

typedef struct _node
{
	_node *leftChild;
	THREAD Lflg;
	elemType data;
	_node *rightChild;
	THREAD Rflag;
}ThBiNode;

ThBiNode *buyNode()
{
	ThBiNode *tmp = (ThBiNode *)malloc(sizeof(ThBiNode));
	if (tmp == NULL) exit(-1);
	memset(tmp, 0, sizeof(ThBiNode));
	return tmp;
}

ThBiNode *createThBiTree(char *&str)
{
	if (str == NULL || *str == '#') return NULL;

	ThBiNode *tmp = buyNode();
	tmp->data = *str;
	if ((tmp->leftChild=createThBiTree(++str)) != NULL) 
	{
		tmp->Lflg=LINK;
	}
	if ((tmp->rightChild = createThBiTree(++str)) != NULL) 
	{
		tmp->Rflag=LINK;
	}
	return tmp;  
}

void createInOrder(ThBiNode* p, ThBiNode* &ptr)
{
	if (p == NULL) return ;
	createInOrder(p->leftChild,ptr);
	if (p->Lflg!=LINK)
	{
		p->leftChild = ptr;
		p->Lflg = THLINK;
	}
	if (ptr!=NULL && ptr->Rflag!=LINK)
	{
		ptr->rightChild = p;
		ptr->Rflag = THLINK;
	}
	ptr=p;
	createInOrder(p->rightChild, ptr);
}

void ThBiTreeInOrder(ThBiNode *p)
{
	if (p == NULL)return ;
	ThBiNode *ptr = NULL;
	createInOrder(p , ptr);//传递的是ptr的引用
	ptr->Rflag = THLINK;
	ptr->rightChild = NULL;
}

ThBiNode *first(ThBiNode *p)
{
	if (p != NULL)
	{
		while (p->Lflg == LINK)
		{
			p = p->leftChild;
		}
	}
	return p;
}

ThBiNode *nextNode(ThBiNode *p)
{
	if (p->Rflag == THLINK)
	{
		return p->rightChild;
	}
	return first(p->rightChild);
}

void inOrder(ThBiNode *ptr)//中序遍历
{
	for (ThBiNode *i= first(ptr); i!=NULL; i=nextNode(i))
	{
		cout<<i->data;
	}
}

ThBiNode *last(ThBiNode *p)
{
	if (p != NULL)
	{
		while(p->Rflag == LINK)
		{
			p = p->rightChild;
		}
	}
	return p;
}

ThBiNode *nextForRe(ThBiNode *p)
{
	if (p->Lflg == THLINK)
	{
		return p->leftChild;
	}
	return last(p->leftChild);
}

void inOrderRes(ThBiNode *ptr)
{
	for (ThBiNode *i =last(ptr); i != NULL; i=nextForRe(i))
	{
		cout<<i->data;
	}
}

int main()
{
	char *str = "ABC##DE##F##G#H##";//先根
	ThBiNode *root = createThBiTree(str);
	ThBiTreeInOrder(root);
	inOrder(root);
	cout<<endl;
	inOrderRes(root);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值