head.h
#ifndef __HEAD_H__
#define __HEAD_H__
#include<stdio.h>
#include<ctype.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
typedef struct Tree{
char data;
struct Tree *left;
struct Tree *right;
}*tree;
tree create();
void out_put(tree);
void out_put1(tree);
void out_put2(tree);
int count(tree);
int count_nums(tree);
void count_num(tree,int*,int*,int*);
tree free_tree(tree);
#endif
main.c
#include"head.h"
int main(int argc, const char *argv[])
{
tree T = create();//创建树
out_put(T);//输出打印先序遍历
putchar(10);
out_put1(T);//中序遍历
putchar(10);
out_put2(T);//后续遍历
putchar(10);
int tree_num =count(T);//计算树的深度
printf("%d\n",tree_num);
int num = count_nums(T);//计算树0度1度2度分别的节点数量
printf("%d\n",num);
putchar(10);
T = free_tree(T);//释放树空间
return 0;
}
fun.c
#include "head.h"
/*
* function:
* @param [ in]
* @param [out]
* @return
*/
tree create()
{
printf("请输入元素:\n");
char e;
scanf("%c",&e);
getchar();
if(e=='#')
return NULL;
tree T = (tree)malloc(sizeof(struct Tree));
if(T==NULL)
return NULL;
T->data=e;
T->left = create();
T->right = create();
return T;
}
/*
* function: out_put//先序
* @param [ in]
* @param [out]
* @return
*/
void out_put(tree T)
{
if(T==NULL)
return ;
printf("%c\t",T->data);
out_put(T->left);
out_put(T->right);
//putchar(10);
}
/*
* function: out_put1中序
* @param [ in]
* @param [out]
* @return
*/
void out_put1(tree T)
{
if(T==NULL)
return ;
out_put1(T->left);
printf("%c\t",T->data);
out_put1(T->right);
//putchar(10);
}
/*
* function: out_put2后续
* @param [ in]
* @param [out]
* @return
*/
void out_put2(tree T)
{
if(T==NULL)
return ;
out_put2(T->left);
out_put2(T->right);
printf("%c\t",T->data);
//putchar(10);
}
/*
* function: count
* @param [ in]
* @param [out]
* @return
*/
int count(tree T)
{
if(T==NULL)
return 0;
int left = count(T->left)+1;
int right = count(T->right)+1;
return left>right?left:right;
}
/*
* function: count_nums
* @param [ in]
* @param [out]
* @return
*/
int count_nums(tree T)
{
if(T== NULL){
return ;
}
int n0=0,n1=0,n2=0;
count_num(T,&n0,&n1,&n2);
printf("n0=%d\tn1=%d\tn2=%d\n",n0,n1,n2);
putchar(10);
return n0+n1+n2;
}
/*
* function: count_num
* @param [ in]
* @param [out]
* @return
*/
void count_num(tree T,int *p0,int *p1,int *p2)
{
if(T== NULL){
return ;
}
count_num(T->left,p0,p1,p2);
count_num(T->right,p0,p1,p2);
if(T->left==NULL&&T->right==NULL)
{
(*p0)++;
}else if(T->left!=NULL&&T->right!=NULL)
{
(*p2)++;
}else{
(*p1)++;
}
}
/*
* function: free_tree
* @param [ in]
* @param [out]
* @return
*/
tree free_tree(tree T)
{
if(T==NULL)
return NULL;
free_tree(T->left);
free_tree(T->right);
free(T);
T=NULL;
return T;
}