二叉树的遍历(递归)

原创
2012/07/18 18:49
阅读数 207
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int datatype;
typedef struct _bitree_node_ {
	datatype data;
	struct _bitree_node_ *lchild;
	struct _bitree_node_ *rchild;
}bitree;
bitree *creat_bitree_node(datatype value)
{
	bitree *root = (bitree *)malloc(sizeof(bitree));
	memset(root,0,sizeof(bitree));
	root->data = value;
	return root;
}

bitree *creat_bitree(datatype min, datatype max)
{
	bitree *root = creat_bitree_node(min);
	if(min * 2 <= max)
		root->lchild = creat_bitree(min * 2,max);
	if(min *2 + 1 <= max)
		root->rchild = creat_bitree(min * 2 + 1,max);
	return root;
}

void pre_order(bitree * root)
{
	if(NULL == root)
		return ;
	printf("%3d",root->data);
	pre_order(root->lchild);
	pre_order(root->rchild);
}
void in_order(bitree * root)
{
	if(NULL == root)
		return ;
	in_order(root->lchild);
	printf("%3d",root->data);
	in_order(root->rchild);
}
void post_order(bitree * root)
{
	if(NULL == root)
		return ;
	post_order(root->lchild);
	post_order(root->rchild);
	printf("%3d",root->data);
}
int main()
{
	bitree *root = creat_bitree(1,10);
	puts("pre_order :");
	pre_order(root);
	putchar(10);
	puts("in_order :");
	in_order(root);
	putchar(10);
	puts("post_order :");
	post_order(root);
	putchar(10);
	return 0;
}

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
3 收藏
1
分享
返回顶部
顶部