平衡二叉树的构建 用函数回调来扩展程序 c语言实现

41 篇文章 1 订阅
20 篇文章 0 订阅

构建平衡二叉树

                             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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值