栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

二叉树的线索化

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二叉树的线索化

树的形状

 

树的创建(线索化版)

#include
#include
#include

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");
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/835310.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号