作业1: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 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();
//前序遍历
puts("first");
first(tree);
puts("");
//中序遍历
puts("mid");
mid(tree);
puts("");
//后序遍历
puts("last");
last(tree);
puts("");
//计算节点
int n0=0,n1=0,n2=0;
count(tree,&n0,&n1,&n2);
printf("n0=%d n1=%d n2=%d n=%d\n",n0,n1,n2,n0+n1+n2);
//二叉树计算深度
int len=high(tree);
printf("len=%d\n",len);
return 0;
}
作业2:编程实现快速排序降序
#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,mid-1);
quick_sort(arr,mid+1,high);
}
int main(int argc, const char *argv[])
{
int arr[]={2,1,4,5,8,9,7,3,6};
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;
}
思维导图: