(18)线索二叉树

以这种结点构成的二叉链表作为二叉树的存储结构,称为线索链表,其中指向结点前驱和后继的指针,称为线索;加上线索的二叉树,称为线索二叉树,以某种次序遍历二叉树使其变为线索二叉树的过程,称为线索化。

代码:

#include<iostream>
using namespace std;
typedef char ElemType;
enum flag{	zero, one};  // zero 代表否 one代表真
typedef struct BiThrNode {
	ElemType data;
	struct BiThrNode *lchild, *rchild;
	flag ltag : 2;  //分别两个字节
	flag rtag : 2;
}BiThrNode,*BiThrTree;
void CreateBiTree(BiThrTree  &T) {  //前序序列构造二叉树
	ElemType ch;
	cin >> ch;
	if (ch == '#') {
		T = NULL;
	}
	else {
		T = (BiThrTree)malloc(sizeof(BiThrNode));
		T->data = ch;
		CreateBiTree(T->lchild);
		if (T->lchild) {
			T->ltag = zero;
		}
		CreateBiTree(T->rchild);
		if (T->rchild) {
			T->rtag = zero;
		}
	}
}
BiThrTree pre = NULL;
void inThreat(BiThrTree p) { //对二叉树进行中序线索化
	if (p) {
		inThreat(p->lchild);
		if (p->lchild == NULL) {
			p->ltag = one;
			p->lchild = pre;
		}
		if (pre->rchild == NULL) {
			pre->rtag = one;
			pre->rchild = p;
		}
		pre = p;
		inThreat(p->rchild);
	}
}
void inOrderThreat(BiThrTree &T,BiThrTree p) {  //连接含有null的结点形成一个闭环
	T = (BiThrTree)malloc(sizeof(BiThrNode));
	T->ltag = zero;
	T->rtag = one;
	T->rchild = T;
	if (p) {
		T->lchild = p;
		pre = T;
		inThreat(p);
		pre->rtag = one;
		pre->rchild = T;
		T->rchild = pre;
	}
	else {
		T->lchild = T;
	}
}
void inOrderThreatTraverse(BiThrTree T) {  //中序遍历二叉树
	BiThrTree p = T->lchild;
	while (p!=T) {
		while (p->ltag == zero) {
			p = p->lchild;
		}
		cout << p->data << " ";
		while (p->rtag==one && p->rchild !=T) {
			p = p->rchild;
			cout << p->data << " ";
		}
		p = p->rchild;
	}
}
void main() {
	BiThrTree H,T;
	cout << "请输入前序序列构造二叉树" << endl;
	CreateBiTree(T);
	inOrderThreat(H, T);
	cout << "中序遍历结果为:" << endl;
	inOrderThreatTraverse(H);
	system("pause");
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值