构建平衡二叉树
6
3 8
1 4 10
多文件编程实现
tree.h
#ifndef __TREE_H__
#define __TREE_H__
void init();
void deinit(tree *);
tree *search(int);
void insert(int);
void printf(void (*)(int*,void *),void *);
#endif
tree.c
#include <stdlib.h>
#include <stdio.h>
struct node;
typedef struct tree{
struct node *p_node;
}tree;
typedef struct node{
int num;
tree left;
tree right;
}node;
static tree rt;
void init(){ // 平衡二叉树的初始化
rt.p_node = NULL;
}
void deinit(tree *p_rt){//平衡二叉树空间的释放
if (!(p_rt->p_node)){
return ;
}
deinit (&(p_rt->p_node->left));
deinit (&(p_rt->p_node->right));
}
static tree *tree_search(tree * p_rt,int num){ //从根查找 并且返回方块的值 static 注明是只能在此文件使用
if (!(p_rt->p_node)){
return p_rt;
}
if (p_rt->p_node->num == num){
return p_rt;
}
if (p_rt->p_node->num > num){
return tree_search(&(p_rt->p_node->left),num);
}
else {
return tree_search(&(p_rt->p_node->right),num);
}
}
tree *search(int num){ // 多文件编程中可调用的函数
return tree_search(&rt,num);
}
void insert(int num){ // 在平衡二叉树中插入数字
tree *p_tmp = search(num);
if (p_tmp->p_node){
return;
}
else{
node *p_node = (node *)malloc(sizeof(node));
p_node->num = num;
p_node->left.p_node = NULL;
p_node->right.p_node = NULL;
p_tmp->p_node = p_node;
}
}
static void tree_print(tree *p_tree,void (*func)(int *num,void *tmp),void *temp ){
if (!(p_tree->p_node)){
return;
}
tree_print(&(p_tree->p_node->left),func,temp);
func(&(p_tree->p_node->num),temp);
tree_print(&(p_tree->p_node->right),func,temp);
}
void print(void (*func)(int *num,void *tmp),void *temp ){ // 函数回调,可以调用自己赋给的函数指针
tree_print(&rt,func,temp);
}
static void hflip(tree *p_rt){ // 左右节点相互翻转
if (!(p_rt->p_node)){
return;
}
node *p_tmp;
p_tmp = p_rt->p_node->left.p_node;
p_rt->p_node->left.p_node = p_rt->p_node->right.p_node;
p_rt->p_node->right.p_node = p_tmp;
hflip(&(p_rt->p_node->left));
hflip(&(p_rt->p_node->right));
}
void flip(){
hflip(&rt);
}
main.c
#include <stdio.h>
void func(int *num,void *temp){
printf("%d ",*num);
}
int main()
{
init();
int num = 0;
char ch = 'Y';
do{
printf("Please input the number you want to input.\n");
scanf("%d", &num);
insert(num);
getchar();
printf("would you want to input another number. Y or N\n");
scanf("%c",&ch);
scanf("%*[^\n]");
scanf("%*c");
}while(ch == 'Y' || ch == 'y');
printf("打印全部值\n");
print(func,NULL);
flip();
printf("\n调用旋转函数\n");
print(func,NULL);
return 0;
}