(第五章)1.创建二叉树

代码实现功能:

创建二叉树、先序(中序、后续、层次)遍历、叶子节点数、节点数、高度(深度) 。

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

typedef struct BT
{
	char data;
	struct BT * lchild, *rchild;
}BT;

BT * Create_tree()  //先序创建树
{
	BT * T;
	char x;
	scanf_s("%c", &x);
	getchar();
	if(x=='0')
		T=NULL;
	else
	{
		T=(BT *)malloc(sizeof(BT));
		T->data=x;
		printf("请输入 %c 的左孩子:", T->data);
		T->lchild=Create_tree();
		printf("请输入 %c 的右孩子:", T->data);
		T->rchild=Create_tree();
	}
	return T;
}

void pre_tree(BT * T)  //先序遍历
{
	if(T==NULL)
		return;
	else
	{
		printf("%c", T->data);
		pre_tree(T->lchild);
		pre_tree(T->rchild);
	}
}
void in_tree(BT * T)  //中序遍历
{
	if(T==NULL)
		return;
	else
	{
		in_tree(T->lchild);
		printf("%c", T->data);
		in_tree(T->rchild);
	}
}

void post_tree(BT * T)  //后序遍历
{
	if(T==NULL)
		return ;
	else
	{
		post_tree(T->lchild);
		post_tree(T->rchild);
		printf("%c", T->data);
	}
}

void level_tree(BT * T)  //层次遍历
{
	int i, j;
	BT * q[50], *p;
	p=T;
	if(T!=NULL)
	{
		i=1;
		q[1]=p;
		j=2;
	}
	while(i!=j)
	{
		p=q[i];
		printf("%c", p->data);
		if(p->lchild!=NULL)
		{
			q[j]=p->lchild;
			j++;
		}
		if(p->rchild!=NULL)
		{
			q[j]=p->rchild;
			j++;
		}
		i++;
	}
}

void leaf_num(BT * T, int * num)  //叶子节点数
{
	if(T!=NULL)
	{
		if(T->lchild==NULL && T->rchild==NULL)
			(*num)++;
		leaf_num(T->lchild, num);
		leaf_num(T->rchild, num);
	}
}

void node_num(BT * T, int * count)  //节点数
{
	if(T==NULL)
		return;
	else
	{
		(*count)++;
		node_num(T->lchild, count);
		node_num(T->rchild, count);
	}
}

int depth_tree(BT * T)  //树的高度(深度)
{
	int ld, rd;
	if(T==NULL)
		return 0;
	else
	{
		ld=depth_tree(T->lchild);
		rd=depth_tree(T->rchild);
	}
	return (ld > rd ? ld: rd)+1;
}

int main()
{
	BT * T;
	int num, count;
	num=count=0;
	printf("创建树:");
	T=Create_tree();
	printf("先序遍历:");
	pre_tree(T);
	printf("\n");
	printf("中序遍历:");
	in_tree(T);
	printf("\n");
	printf("后序遍历:");
	post_tree(T);
	printf("\n");
	printf("层次遍历:");
	level_tree(T);
	printf("\n");
	leaf_num(T, &num);
	printf("叶子节点数:%d\n", num);
	node_num(T , &count);
	printf("节点数:%d\n", count);
	printf("二叉树的深度:%d\n", depth_tree(T));
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值