树的先序遍历(递归和非递归)

本文介绍了如何用C语言实现二叉树的数据结构,包括树的创建函数creattree和两种遍历方式:先序递归和非递归遍历。通过实例展示了如何构造一个树并进行先序遍历,适合初学者理解基本的树结构操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

树的形状

 

构建树代码

//树类型的定义
typedef struct bitree
{
	int val;
	struct bitree* lchild;
	struct bitree* rchild;
	int rl;
}BT, * bt;
//树的创建
bt 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=creattree( a, b, a1 + 1, a1 + llen, b1, b1 + llen - 1);
	}
	else
	{
		root->lchild = NULL;
	}
	if (rlen)
	{
		root->rchild=creattree( a, b, a2 - rlen + 1, a2, b2 - rlen + 1, b2);
	}
	else
	{
		root->rchild = NULL;
	}
	return root;

}

遍历代码

//先序递归遍历
void previst(bt root)
{
	if (root == NULL)
		return;
	printf("%d ", root->val);
	if (root->lchild != NULL)
	{
		previst(root->lchild);
	}
	if (root->rchild!=NULL)
	{
		previst(root->rchild);
	}
}
//先序非递归遍历
void non_previst(bt root)
{
	bt a[10];
	int top = -1;
	while(root||top>=0)
	{
		if (root)
		{
			printf("%d ", root->val);
			a[++top] = root;
			root = root->lchild;
		}
		else
		{
			root = a[top--];
			root = root->rchild;
		}
	}

}


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 a[10] = { 1,2,4,7,3,5,8,9,6,10 };
	int b[10] = { 7,4,2,1,8,5,9,3,6,10 };*/
	int a1 = 0;
	int a2 = 9;
	int b1 = 0;
	int b2 = 9;
	bt root=NULL;
	root=creattree(a, b, a1, a2, b1, b2);
	/*previst(root);
	printf("\n");
non_previst(root);
	printf("\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值