前序线索化,中序线索化,后续线索化

二叉树的前序线索化,寻找prior,next函数 

#include<iostream>
using namespace std;
struct Threadnode
{
	struct Threadnode *lchild, *rchild;
	bool ltag, rtag;
};
Threadnode *pre;
void Thread(Threadnode *&root )//前序线索化
{
	if (!root)
		return;
	else
	{
		if (!root->lchild)
		{
			root->lchild = pre;
			root->ltag = 1;
		}
		if (!pre->rchild)
		{
			pre->rchild = root;
			pre->rtag = 1;
		}
		pre = root;
		Thread(root->lchild);
		Thread(root->rchild);
	}
}

void next(Threadnode *node, Threadnode *&x)
{
	if (node->ltag)
		x = node->rchild;
	else
		x = node->lchild;
}
void prior(Threadnode *bt,Threadnode *node, Threadnode *&x)
{
	x = bt;
	Threadnode *t;
	if (node->ltag)
		x = node->lchild;
	else
	{
		while (x != node)
		{
			t = x;
			next(t, x);
		}
		x = t;
	}
}
int main()
{
	system("pause");
	return 0;
}

 

中序线索化与二叉树中序线索化寻找前驱和后继

#include<iostream>
using namespace std;
struct Threadnode
{
	struct Threadnode *lchild, *rchild;
	bool ltag, rtag;
};
Threadnode *pre;
void Thread(Threadnode *&root )//中序线索化
{
	if (!root)
		return;
	else
	{
		Thread(root->lchild);
		if (!root->lchild)
		{
			root->lchild = pre;
			root->ltag = 1;
		}
		if (!pre->rchild)
		{
			pre->rchild = root;
			pre->rtag = 1;
		}
		pre = root;
		Thread(root->rchild);
	}
}
void prior(Threadnode *node, Threadnode *&x)
{
	if (node->ltag)
		x = node->lchild;
	else
	{
		x = node->lchild;
		while (x->rchild)
			x = x->rchild;
	}
}
void next(Threadnode *node, Threadnode *&x)
{
	if (node->rtag)
		x = node->rchild;
	else
	{
		x = node->rchild;
		while (x->lchild)
			x = x->lchild;
	}
}
int main()
{
	system("pause");
	return 0;
}

二叉树后序线索化,prior,next函数 

#include<iostream>
using namespace std;
struct Threadnode
{
	struct Threadnode *lchild, *rchild;
	bool ltag, rtag;
};
Threadnode *pre;
void Thread(Threadnode *&root )//后序线索化
{
	if (!root)
		return;
	else
	{
		
		Thread(root->lchild);
		Thread(root->rchild);
		if (!root->lchild)
		{
			root->lchild = pre;
			root->ltag = 1;
		}
		if (!pre->rchild)
		{
			pre->rchild = root;
			pre->rtag = 1;
		}
		pre = root;
	}
}
void prior(Threadnode *node, Threadnode *&x)
{
	if (node->rtag)
		x = node->lchild;
	else
		x = node->rchild;
}

void next(Threadnode *bt, Threadnode *node, Threadnode *&x)
{
	x = bt;
	Threadnode *t;
	if (node->rtag)
		x = node->rchild;
	else
	{
		while (x != node)
		{
			t = x;
			prior(t, x);
		}
		x = t;
	}
}

int main()
{
	system("pause");
	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值