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

树形状

树的创建

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值