16.线索二叉树 (中序) 及 线索二叉树的中序遍历


#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<stack>
#define OK 0
#define ERROR 1
using namespace std;
typedef char ElemType;
FILE *fp;
void InitFile()
{
	fopen_s(&fp, "data.txt", "r");
	//fopen_s(&fp, "tdata.txt", "w+");
	if (!fp) exit(ERROR);
	return;
}
typedef bool Status;

/******
file input:
abc00d00ef00g00
*******/


//     线索二叉树

//  线索二叉树的优点是什么  通过  insucc 快速找到该节点的直接后继

typedef  struct node
{
	ElemType data;
	int lflag, rflag;
	struct node *lchild, *rchild;

}TreeNode, *tree_ptr;

Status CreateBitTree(tree_ptr &t)//创建一颗二叉树
{
	char c;
	//c = fgetchar();
	fscanf_s(fp, "%c", &c);
	printf("%c", c);
	if (c == '0'){ t = NULL;  return OK; }
	else
	{
		t = (tree_ptr)malloc(sizeof(TreeNode));
		if (!t) exit(ERROR);
		t->data = c; t->lflag = t->rflag = 0;
		CreateBitTree(t->lchild);
		CreateBitTree(t->rchild);
	}
	return OK;
}

//用递归 中序遍历 二叉树  实现 二叉树的中序线索化
Status InThreading(tree_ptr t,tree_ptr &pre)
{
	if (t)
	{
		InThreading(t->lchild,pre);
		if (!t->lchild)
		{
			t->lflag = 1;
			t->lchild = pre; 
		}
		if (!pre->rchild)
		{ 
			pre->rflag = 1;
			pre->rchild = t;
		}
		pre = t;
		InThreading(t->rchild, pre);
	}
	return OK;
}
//线索二叉树的思想是指 将空的指针   左指针指向 他的直接前驱  右指针指向它的直接后继 //起始Ts节点右指针可以自定义  默认指向遍历过程中 最后一个 节点
Status InorderThreading(tree_ptr &Ts,tree_ptr t)
{
	Ts = (tree_ptr)malloc(sizeof(TreeNode));
	if (!Ts) exit(ERROR);
	Ts->lflag = 0; Ts->rflag = 1;  
	Ts->rchild = NULL; //右指针.........
	if (!t) Ts->lchild = NULL;//空树 , 则左指针指向树根
	else
	{
		//Ts->lchild = t;
		tree_ptr  pre;//p为当前访问的节点 pre为上一个访问的节点
		pre = Ts;
		InThreading(t,pre);
		pre->rchild = Ts;	pre->rflag = 1;
		//Ts->rchild = pre;//不要随随便便写你不明白的代码....一切不负责任的输入都是恶(⊙o⊙)…
		Ts->lchild = pre;
	}
	return 0;
}

///
//	中序遍历
Status Inorder(tree_ptr t)
{
	if (t)
	{
		Inorder(t->lchild);
		printf("%c ", t->data);
		Inorder(t->rchild);
	}
	return OK;
}

//
//    先序遍历
Status Preorder(tree_ptr t)
{
	if (t)
	{
		printf("%c ", t->data);
		Preorder(t->lchild);
		Preorder(t->rchild);
	}
	return OK;
}
/
tree_ptr insucc(tree_ptr t)
{
	tree_ptr temp;
	temp = t;
	if (temp->rflag)
		return temp->rchild;
	else
	{
		temp = temp->rchild;
		while (!temp->lflag) temp = temp->lchild;
		return temp;
	}
}

void  tinorder(tree_ptr ts)
{
	tree_ptr temp;
	temp = ts;
	for (;;)
	{
		temp = insucc(temp);
		if (temp == ts) break;
		printf("%c ", temp->data);
	}


}
//by zhaoyang 2014.4.19
int main()
{
	InitFile();

	tree_ptr A,AS;
	CreateBitTree(A);

	printf("\n先序遍历:\n");
	Preorder(A);
	printf("\n中序遍历\n");
	Inorder(A);
	printf("\n中序遍历线索化二叉树:-------------------\n");
	InorderThreading(AS,A);

	//线索化遍历
	tinorder(AS);
	printf("\n遍历完毕\n");

	printf("\n");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值