二叉树:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char datatype;
typedef struct Node
{
//数据域:存储数据元素
datatype data;
//指针域:存储左子树的地址
struct Node *lchild;
//指针域:存储右子树的地址
struct Node *rchild;
}*Btree;
/*
* function: 创建新节点
* @param [ in]
* @param [out] 成功返回地址,失败返回NULL
* @return
*/
Btree create()
{
Btree s=(Btree)malloc(sizeof(struct Node));
if(s==NULL)
return NULL;
s->data='\0';
s->lchild=s->rchild=NULL;
return s;
}
/*
* function: 二叉树的创建
* @param [ in]
* @param [out] 根
* @return
*/
Btree create_Node()
{
char element;
printf("please enter element:");
scanf(" %c",&element);
if(element=='#')
return NULL;
Btree tree=create();
tree->data=element;
printf("%C左",element);
tree->lchild=create_Node();
printf("%c右",element);
tree->rchild=create_Node();
return tree;
}
/*
* function: 先序遍历
* @param [ in] tree
* @param [out] 无
* @return
*/
void first(Btree tree)
{
if(tree==NULL)
return;
//打印根
printf("%c",tree->data);
//遍历左孩子
first(tree->lchild);
//遍历右孩子
first(tree->rchild);
}
/*
* function: 中序遍历
* @param [ in] tree
* @param [out] 无
* @return
*/
void mid(Btree tree)
{
if(tree==NULL)
return;
mid(tree->lchild);
printf("%c",tree->data);
mid(tree->rchild);
}
/*
* function: 后续遍历
* @param [ in] tree
* @param [out] 无
* @return
*/
void after(Btree tree)
{
if(tree==NULL)
return;
after(tree->lchild);
after(tree->rchild);
printf("%c",tree->data);
}
/*
* function: 计算各个节点个数
* @param [ in] tree n0 n1 n2
* @param [out] 无
* @return
*/
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 && tree->rchild)
++*n2;
else
++*n1;
Count(tree->lchild,n0,n1,n2);
Count(tree->rchild,n0,n1,n2);
}
/*
* function: 计算深度
* @param [ in] tree
* @param [out] 深度
* @return
*/
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_Node();
puts("first");
first(tree);
puts("");
puts("middle");
mid(tree);
puts("");
puts("after");
after(tree);
int n0=0,n1=0,n2=0;
Count(tree,&n0,&n1,&n2);
puts("");
printf("n0=%d n1=%d n2=%d n=%d",n0,n1,n2,n0+n1+n2);
puts("");
printf("high=%d\n",high(tree));
return 0;
}
快排:
#include<stdio.h>
#include<stdlib.h>
#include<string.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[]={34,23,56,75,17,28,39,51,93,17};
int len=sizeof(arr)/sizeof(arr[0]);
quick_sort(arr,0,len-1);
for(int i=0;i<len;i++)
{
printf("%d ",arr[i]);
}
return 0;
}
思维导图: