数据结构二叉树与排序

思维导图

二叉树练习

代码

#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 enter element");
	scanf(" %c",&element);
	if(element=='#')
		return NULL;
	Btree s=create_node();
	s->data=element;
	puts("左孩");
	s->lchild=create_tree();
	puts("右孩");
	s->rchild=create_tree();
	return s;
}
void First(Btree tree)
{
	if(tree==NULL)
		return;
	printf("%c",tree->data);
	First(tree->lchild);
	First(tree->rchild);
}
void mid_output(Btree tree)
{
	if(tree==NULL)
		return;
	mid_output(tree->lchild);
	printf("%c",tree->data);
	mid_output(tree->rchild);
}
void last_output(Btree tree)
{
	if(tree==NULL)
		return;
	last_output(tree->lchild);
	last_output(tree->rchild);
	printf("%c",tree->data);
}
void count(Btree tree,int *n0,int *n1,int *n2)
{
	if(tree==NULL)
		return;
	if(tree->lchild==NULL&&tree->rchild==NULL)
		++*n0;
	else if(tree->lchild!=NULL&&tree->rchild!=NULL)
		++*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 s=create_tree();
	printf("二叉树先序遍历输出:");
	First(s);
	puts("");
	printf("二叉树中序遍历输出:");
	mid_output(s);
	puts("");
	printf("二叉树后序遍历输出:");
	last_output(s);
	puts("");
	int n0=0,n1=0,n2=0;

	count(s,&n0,&n1,&n2);
	printf("二叉树的节点个数:\n");
	printf("n0=%d n1=%d n2=%d all=%d\n",n0,n1,n2,n0+n1+n2);
	printf("二叉树的深度:\n");
	int len=high(s);
	printf("len=%d\n",len);

	return 0;
}

效果图

快速排序练习

降序

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int one_sort(int arr[],int low,int high)
{
	int key=arr[low];
	while(low<high)
	{
		while(low<high&&key >= arr[high])
			high--;
		arr[low]=arr[high];
		while(low<high&&key<=arr[low])
			low++;
		arr[high]=arr[low];
	}
	arr[low]=key;
	return low;
}

void quick_sort(int arr[],int low,int high)
{
	if(low==high)
		return;
	int mid=one_sort(arr,low,high);
	quick_sort(arr,low,high-1);
	quick_sort(arr,low+1,high);
}
int main(int argc, const char *argv[])
{
	int arr[]={11,22,33,12,23,34,55,44,2,3,4};
	int len=sizeof(arr)/sizeof(arr[0]);
	quick_sort(arr,0,len-1);
	for(int i=0;i<len;i++)
	{
		printf("%d ",arr[i]);
	}
	puts("");
	return 0;
}

效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值