c 二叉树的使用

时间:2023-03-09 01:23:49
c 二叉树的使用

简单的通过一个寻找嫌疑人的小程序 来演示二叉树的使用

 #include <stdio.h>
#include <stdlib.h>
#include <string.h> /**
* 数据结构 - 二叉树 - 节点
*/
typedef struct node {
char *querstion;
struct node *no;
struct node *yes;
}node; /**
* 方法 输入和输入
* 根据打印,询问答案是否正确,y是正确
*/ int yes_no(char *question) {
printf("%s ? (y/n)",question);
char answer[];
fgets(answer, , stdin);
return answer[] == 'y';
} /**
* 根据问题创建节点
*
* @param question 问题描述
*
* @return 返回一个node
*/
node *create(char *question) {
node *n = malloc(sizeof(node));
n->querstion = strdup(question);
n->no = NULL;
n->yes = NULL;
return n;
} /**
* 释放内存
*
* @param n 节点
*/
void release(node *n) {
if (n) {
if (n -> yes) {
free(n->yes);
}
if (n -> no) {
free(n->no);
}
if (n -> querstion) {
free(n->querstion);
}
free(n);
}
} int main(int argc, const char * argv[]) { // 初始化...
char question[];
char suspect[]; // 初始化第一个数据
// 嫌疑犯如果有胡子就是张三,否则是李四
node *start = create("嫌疑犯有胡子");
start->no = create("李四");
start->yes = create("张三"); node *current;
do { current = start;
// 循环的访问节点
while () {
if (yes_no(current->querstion)) { //y
if (current->yes) {
current = current->yes;
}else {
printf("找到了嫌疑犯!\n");
break;
}
}else if (current->no) { // 跳到no 分支
current = current->no;
}else{ // 添加更多信息 // 添加嫌疑犯
printf("谁是嫌疑犯?");
fgets(suspect, , stdin);
node *yes_node = create(suspect);
current->yes = yes_node; // n
node *no_node = create(current->querstion);
current->no = no_node; // question
printf("请输入一个问题,如果正确嫌疑犯是:%s,否则嫌疑犯是:%s",suspect,current->querstion);
fgets(question, , stdin);
current->querstion = strdup(question);
break;
}
} } while (yes_no("再来一次")); release(start); return ;
}

运行程序,我们来查看打印信息

c 二叉树的使用

然而,表面上看这段代码没什么问题,其实有一部分存储器没事释放的,下边我们使用Valgrind工具来看一下

Valgrind 可以在这里下载http://valgrind.org/downloads/current.html#current

Valgind 是一款内存调试,内存泄露检测 和性能调优的 开源软件

使用方法是:

下载并解压好文件后 -》 cd 到文件目录 然后依次运行下边的命令

#./configure --prefix=/usr/local/webserver/valgrind
#make
#make install

可能会报这样的错误,我使用的环境是mac

make[]: *** No rule to make target `/usr/include/mach/mach_vm.defs', needed by `m_mach/mach_vmUser.c'.  Stop.
make[]: *** [install-recursive] Error
make: *** [install] Error

运行下边的命令

xcode-select --install

等待一段时间后,安装完成后

./configure --disable-tls --enable-only64bit --build=amd64-darwin
make
sudo make install

ok 成功安装,接下来让我们使用Valgrind

gcc -g suspect.c -o sus

valgrind --leak-check=full ./sus

之后就能看到检测后的信息了