(p138)递归完成树的遍历

递归还是很简单的,分分钟写出来,可是非递归那就有点难了,加油加油!下面是递归的代码:

/*
 * source.c
 *
 *  Created on: Feb 22, 2016
 *      Author: wing
 */
#include<stdio.h>
#include<stdlib.h>
#define max 10/*二叉树节点数目*/
struct node{
	int n;
	struct node *p,*l,*r;
};
int presearch(struct node *p)/*先序遍历*/
{
	printf("%d ",p->n);
	if (p->l!=NULL)
		presearch(p->l);
	if (p->r!=NULL)
		presearch(p->r);
	return 0;
}
int possearch(struct node *p)/*后序遍历*/
{
	if (p==NULL)
		return 0;
	possearch(p->l);
	possearch(p->r);
	printf("%d ",p->n);
	return 0;
}
int insearch(struct node *p)/*中序遍历*/
{
	if (p==NULL)
		return 0;
	insearch(p->l);
	printf("%d ",p->n);
	insearch(p->r);
	return 0;
}
int build(struct node *root,int n)/*由一个x[i]=i的数组建立二叉树,方法和建堆的方法一样*/
{
	int i;
	for (i=1;i<=n;i++)
		root[i].n=i;
	for (i=1;i<=n/2;i++)
	{
		root[i].p=root+i/2;
		if (i*2<=n)
			root[i].l=root+i*2;
		else
			root[i].l=NULL;
		if (i*2+1<=n)
			root[i].r=root+i*2+1;
		else
			root[i].r=NULL;
	}
	return 0;
}
int main(void)
{
	struct node *root;
	root=(struct node *)malloc(sizeof(struct node)*(max+1));
	build(root,max);
	printf("先序遍历: ");
	presearch(root+1);
	printf("\n后序遍历: ");
	possearch(root+1);
	printf("\n中序遍历: ");
	insearch(root+1);
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值