作业1:1.二叉树递归创建 2.二叉树先中后序遍历 3.二叉树计算节点4.二叉树计算深度。
#include
#include
#include
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 tree=create_node();
tree->data=element;
//递归实现循环创建左孩子
puts("left");
tree->lchild=create_tree();
//递归实现循环创建右孩子
puts("right");
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);
printf("n0=%d,n1=%d,n2=%d,n=%d",n0,n1,n2,n0+n1+n2);
int len=high(tree);
printf("len=%d\n",len);
return 0;
}
作业2:编程实现快速排序降序
#include
#include
#include
//一次排序
//返回基准值下标
int one_sort(int arr[],int low,int high)
{
//确定基准值
int key=arr[low];
//当low==high 结束
//循环low=arr[high])
high--;
arr[low]=arr[high];
//从low开始比较
while(low=high)
return;
//一次排序
int mid=one_sort(arr,low,high);
//递归左边子序列
quick_sort(arr,low,mid-1);
//递归右边子序列
quick_sort(arr,mid+1,high);
}
int main(int argc, const char *argv[])
{
int arr[]={12,3,45,23,345,2,56,34,7};
int len=sizeof(arr)/sizeof(arr[0]);
quick_sort(arr,0,len-1);
for(int i=0;i