1.30作业

 作业要求:1.二叉树递归创建  2.二叉树先中后序遍历 3.二叉树计算节点4.二叉树计算深度。

程序代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef char datatype;


//定义节点结构体
typedef struct Node
{
	datatype data;//数据域:数据元素
	struct Node *lchild;//指针域:存储左孩子的节点地址
	struct Node *rchild;//指针域:存储右孩子的节点地址
}*Btree;


//创建节点
Btree create_node()
{
	Btree s=(Btree)malloc(sizeof(struct Node));
	if(s==NULL)
		return NULL;
	s->data='\0';
	s->lchild=s->rchild=NULL;
	return s;
}

//创建二叉树
Btree create_tree()
{
	datatype element;//插入的数据域
	printf("please input element:");
	scanf(" %c",&element);
	if(element=='#')
		return NULL;
	//创建节点
	Btree tree=create_node();
	tree->data=element;
	//递归实现循环创建左孩子
	tree->lchild=create_tree();
	//递归实现循环创建右孩子
	tree->rchild=create_tree();
	return tree;
}
//先序遍历
void first(Btree tree)
{
	if(tree==NULL)
		return;
	printf("%c",tree->data);
	first(tree->lchild);
	first(tree->rchild);
}


//中序遍历
void mid(Btree tree)
{
	if(tree==NULL)
		return;
	mid(tree->lchild);
	printf("%c",tree->data);
	mid(tree->rchild);
}

//后序遍历
void last(Btree tree)
{
	if(tree==NULL)
		return;
	last(tree->lchild);
	last(tree->rchild);
	printf("%c",tree->data);

}

//计算各个节点个数
void Count(Btree tree,int *n0,int *n1,int *n2)
{
	if(tree==NULL)
		return;
	if(!tree->lchild && !tree->rchild)
		++*n0;
	else if(tree->lchild && tree->rchild)
		++*n2;
	else
		++*n1;
	Count(tree->lchild,n0,n1,n2);
	Count(tree->rchild,n0,n1,n2);
}

//计算深度
int high(Btree tree)
{
	if(tree==NULL)
		return 0;
	//递归计算左子树深度
	int left=1+high(tree->lchild);
	//递归计算右子树深度
	int right=1+high(tree->rchild);
	return left>right?left:right;
}
int main(int argc, const char *argv[])
{
	Btree tree=create_tree();

	first(tree);
	puts("");

	mid(tree);
	puts("");

	last(tree);
	puts("");


	int n0=0,n1=0,n2=0;
	Count(tree,&n0,&n1,&n2);
	int len=high(tree);
	printf("n0=%d,n1=%d,n2=%d,n=%d,len=%d\n",n0,n1,n2,n0+n1+n2,len);
	return 0;
}

运行结果:

作业要求:编程实现快速排序降序。

程序代码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//一次排序
//返回基准值下标
int one_sert(int a[],int low,int high)
{
	int key=a[low];
	while(low<high)
	{
		while(low<high&&key>=a[high])
			high--;
		a[low]=a[high];
		while(low<high&&key<=a[low])
			low++;
		a[high]=a[low];
	}
	a[low]=key;
	return low;
}




//快速排序
void quick_sort(int a[],int low,int high)
{
	if(low>=high)
		return;
	int mid=one_sert(a,low,high);
	quick_sort(a,low,mid-1);
	quick_sort(a,mid+1,high);
}


int main(int argc, const char *argv[])
{
	int a[]={34,45,56,12,23,1,2,3,0};
	int len=sizeof(a)/sizeof(a[0]);
	quick_sort(a,0,len-1);
	for(int i=0;i<len;i++)
	{
		printf("%-3d",a[i]);
	}
	puts("");
	return 0;
}

运行结果:

课程总结:

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值