一、二叉树操作:
1. 二叉树递归创建 2. 二叉树先中后序遍历 3. 二叉树计算节点 4. 二叉树计算深度。
代码:
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
//定义二叉树节点结构体
typedef struct Node
{
int data;
struct Node*left;
struct Node*right;
}*Tree;
Tree create_node()
{
Tree s=(Tree)malloc(sizeof(struct Node));
if(s==NULL)
return NULL;
s->data=0;
s->left=NULL;
s->right=NULL;
return s;
}
Tree create_tree()
{
int element;
printf("please enter element:");
scanf("%d",&element);
if(element==0)
return NULL;
Tree tree=create_node();
tree->data=element;
tree->left=create_tree();
tree->right=create_tree();
return tree;
}
void first_out(Tree tree)
{
if(tree==NULL)
return;
printf("%d",tree->data);
first_out(tree->left);
first_out(tree->right);
}
void mid_out(Tree tree)
{
if(tree==NULL)
return;
first_out(tree->left);
printf("%d",tree->data);
first_out(tree->right);
}
void last_out(Tree tree)
{
if(tree==NULL)
return;
first_out(tree->left);
first_out(tree->right);
printf("%d",tree->data);
}
void Count(Tree tree,int *n0,int *n1,int *n2)
{
if(NULL==tree)
return;
if(tree->left&&tree->right)
++*n2;
else if(!tree->left && !tree->right)
++*n0;
else
++*n1;
Count(tree->left,n0,n1,n2);
Count(tree->right,n0,n1,n2);
}
int high(Tree tree)
{
if(NULL==tree)
return 0;
int leftlen=1+high(tree->left);
int rightlen=1+high(tree->right);
return leftlen>rightlen?leftlen:rightlen;
}
int main(int argc, const char *argv[])
{
//二叉树创建返回树的根节点地址
Tree tree=create_tree();
first_out(tree);//先序遍历
puts("");
mid_out(tree);//中序
puts("");
last_out(tree);//后序
puts("");
int n0=0,n1=0,n2=0;
Count(tree,&n0,&n1,&n2);//计算度数为0/1/2的节点数;
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;
}
运行结果:
二、 编程实现快速排序降序
代码:
#include<stdlib.h>
#include<string.h>
#include<stdio.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 index=one_sort(arr,low,high);
quick_sort(arr,low,index-1);
quick_sort(arr,index+1,high);
}
int main(int argc, const char *argv[])
{
int arr[]={2,22,53,56,21,21,35,568,999,666};
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;
}
运行:
思维导图: