按前序与中序遍历将二叉树线索化并输出

typedef struct BiTNode{
	char data;
	BiTNode* lchild, *rchild;
	int lflag, rflag;
}BiTree;


//中序线索化
void InThreading(BiTree* t){
	if (t != NULL)
	{
		InThreading(t->lchild);//找到属于叶节点的左孩子
		if (t->lchild == NULL)
			t->lflag = 1;
		if (t->rchild == NULL)
			t->rflag = 1;
		if (current != NULL){
			if (t->lflag == 1)
				t->lchild = current;
			if (current->rflag == 1)
				current->rchild = t;
		}
		current = t;
		InThreading(t->rchild);
	}
}

//前序线索化
void FiThreading(BiTree* t){
	if (t != NULL){
		if (t->lchild == NULL)
		{
			t->lflag = 1;
			if (current != NULL)
			t->lchild = current;
		}
			
		if (t->rchild == NULL)
		{
			t->rflag = 1;
			if (current ->rflag==1)
				current->rchild = t;
		}
		current = t;
		//cout << "currrent=" << current->data << endl;
		if (t->lflag==0)//一定要加上标志位判断,否则会陷入死循环
		FiThreading(t->lchild);
		if (t->rflag==0)//一定要加上标志位判断,否则会陷入死循环
		FiThreading(t->rchild);
	}
}

//中序线索二叉树遍历
/*
思路:先查找中序遍历序列的开始节点,沿左指针往下查找,
直到找到无左孩子的节点即二叉树中最左下的节点,将其
输出。继续查找节点的中序后继节点,直到终端节点。
节点的中序后继节点分两种情况:若节点t的右子树为空,
则t->rchild直接指向t的中序后继节点;若节点t的右子树
不为空,则从其右子树开始,沿左指针往下查找,直到找到
节点t的右子树最左下的节点,就是它的中序后继节点
*/
void VisitByIn(BiTree* t){
	while (t != NULL){
		while (t->lflag == 0)
			t = t->lchild;
		if (t == NULL)
			return;
		cout << t->data << endl;
		while (t->rflag == 1 && t->rchild != NULL){
			t = t->rchild;
			cout << t->data << endl;
		}
		t = t->lchild;
	}
}

//前序线索二叉树遍历
/*
思路:
先依次沿左指针输出节点信息,直到找到无左孩子的节点,
将其输出。继续查找节点的前序后继节点,将其输出。
此前序后继节点t的情况分两种,若t的左子树不为空,
则从其左子树开始,沿左指针向下查找并输出,直到最下。
若t的左子树为空,则t->rchild指向t的前序后继节点,
输出
*/
void VisitByFi(BiTree* t){
	while (t != NULL){
		while (t->lflag==0){
			cout << t->data << endl;
			t = t->lchild;
		}
		if (t == NULL)
			return;
		cout << t->data << endl;
		t = t->rchild;
		if (t == NULL)
			return;
		cout << t->data << endl;
		while (t->lflag == 1 && t->rchild != NULL)//注意这儿是要判断左标置位
		{
			t = t->rchild;
			cout << t->data << endl;
		}
		t = t->lchild;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值