二叉树的线索化

树的形状

 

树的创建(线索化版)

#include<stdio.h>
#include<malloc.h>
#include<vector>

typedef struct bitree
{
	int val;
	struct bitree* lchild;
	struct bitree* rchild;
	int rl;
	int ltag = 0;
	int rtag = 0;
}BT, * bt;
bt thread_creattree(int* a, int* b, int a1, int a2, int b1, int b2)
{

	bt root = (bt)malloc(sizeof(BT));
	root->val = a[a1];
	int llen = 0, rlen = 0;
	int i = 0;
	for (; b[i] != a[a1]; i++);
	llen = i - b1;
	rlen = b2 - i;


	if (llen)
	{
		root->lchild = thread_creattree(a, b, a1 + 1, a1 + llen, b1, b1 + llen - 1);
		root->ltag = 0;	
	}
	else
	{
		root->lchild = NULL;
		root->ltag = 0;
	}
	if (rlen)
	{
		root->rchild = thread_creattree(a, b, a2 - rlen + 1, a2, b2 - rlen + 1, b2);
		root->rtag = 0;
	}
	else
	{
		root->rchild = NULL;
		root->rtag = 0;
	}
	return root;

}

树线索化

void prethread(bt& root, bt& pre)
{
	if (root != NULL && root->rl != 1)
	{
		root->rl = 1;
		if (root->lchild == NULL)
		{
			root->lchild = pre;
			root->ltag = 1;

		}
		if (pre != NULL && pre->rchild == NULL)
		{
			pre->rchild = root;
			pre->rtag = 1;
		}
		pre = root;
		prethread(root->lchild, pre);
		prethread(root->rchild, pre);
	}
}
void preclue(bt& root)
{
	if (root != NULL)
	{

		bt pre = NULL;
		prethread(root, pre);
		pre->rchild = NULL;
		pre->rtag = 1;
	}
}

线索化遍历

bt prefirstnode(bt root)
{
	if (root->ltag == 1)
		root = root->rchild;
	else root = root->lchild;
	return root;
}
bt prenextnode(bt root)
{
	if (root->rtag == 1) return root->rchild;
	else
	{
		return prefirstnode(root);
	}
}
void preorder(bt root)
{
	for (bt first = root; first != NULL; first = prenextnode(first))
	{
		printf("%d ", first->val);
	}
}

main函数

int main()
{
	int a[10] = { 1,2,4,7,10,3,5,8,9,6 };
	int b[10] = { 10,7,4,2,1,8,5,9,3,6 };
	int a1 = 0;
	int a2 = sizeof(a) / sizeof(a[0]);
	int b1 = 0;
	int b2 = sizeof(b) / sizeof(b[0]);
	bt root = NULL;
	root = thread_creattree(a, b, a1, a2 - 1, b1, b2 - 1);
	preclue(root);
	preorder(root);
	printf("\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值