数据结构和算法--二叉树创建和递归遍历

//完全二叉树的创建以及遍历(递归)

#include <stdio.h>
#include <stdlib.h>

//定义数据类型
typedef int datatype_t;

//定义结构体
typedef struct node{
	datatype_t data;
	struct node *lchild;
	struct node *rchild;
}bitree_t;

//创建一个二叉树(n表示结点总数,i表示根结点)
bitree_t *bitree_create(int n, datatype_t i)
{
	bitree_t *bt;
	bt = (bitree_t *)malloc(sizeof(bitree_t));
	bt->data = i;
	
	if(2 * i <= n)
	{
		bt->lchild = bitree_create(n, 2 * i);
	}
	else
	{
		bt->lchild = NULL;
	}

	if(2 * i + 1 <= n)
	{
		bt->rchild = bitree_create(n, 2 * i + 1);
	}
	else
	{
		bt->rchild = NULL;
	}

	return bt;
}

//先序遍历
int bitree_before_order(bitree_t *root)
{
	if(root == NULL)
	{
		return 0;
	}

	printf("%d ", root->data);

	if(root->lchild != NULL)
	{
		bitree_before_order(root->lchild);
	}

	if(root->rchild != NULL)
	{
		bitree_before_order(root->rchild);
	}

	return 0;
}

//中序遍历
int bitree_in_order(bitree_t *root)
{
	if(root == NULL)
	{
		return 0;
	}

	if(root->lchild != NULL)
	{
		bitree_in_order(root->lchild);
	}

	printf("%d ", root->data);

	if(root->rchild != NULL)
	{
		bitree_in_order(root->rchild);
	}

	return 0;
}

//后序遍历
int bitree_after_order(bitree_t *root)
{
	if(root == NULL)
	{
		return 0;
	}

	if(root->lchild != NULL)
	{
		bitree_after_order(root->lchild);
	}

	if(root->rchild != NULL)
	{
		bitree_after_order(root->rchild);
	}

	printf("%d ", root->data);

	return 0;
}

int main(int argc, const char *argv[])
{
	bitree_t *root;
	root = bitree_create(8, 1);

	bitree_before_order(root);
	putchar(10);

	bitree_in_order(root);
	putchar(10);

	bitree_after_order(root);
	putchar(10);
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值