二叉树的后序遍历(递归和非递归)

本文探讨了如何通过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 endvist(bt root)
{
	if (root == NULL)
		return;

	if (root->lchild != NULL)
	{
		endvist(root->lchild);
	}
	if (root->rchild != NULL)
	{
		endvist(root->rchild);
	}
	printf("%d ", root->val);
}
//非递归
void non_endvist(bt root)
{
	bt a[10];
	int top = -1;
	while (root || top >= 0)
	{
		if (root)
		{
			a[++top] = root;
			root->rl = 0;
			root = root->lchild; 
		}
		else
		{
			 root = a[top];
			
			if (root->rchild&&root->rchild->rl!=1)
			{   
		
				root = root->rchild;
			}
			else
			{   
				root = a[top--];
				printf("%d ", root->val);
				root->rl = 1;
				root = NULL;
				
			}
         
		}
	}
}
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 = 9;
	int b1 = 0;
	int b2 = 9;
	bt root=NULL;
	root=creattree(a, b, a1, a2, b1, b2); //创建
	endvist(root);//递归
	printf("\n");
	non_endvist(root);//非递归
    printf("\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值