我正在关注一本书,Problem Solving & Program Design in C,来学习 C。在这本书中,他们给出了构建二叉搜索树的所有必要部分......但是,我的实现没有奏效。这是插入部分;
void
add_to_t(tree_node_t *oldTreep, // input/output - binary search tree
tree_element_t ele) // input - element to add
{
oldTreep = tree_insert(oldTreep, ele);
}
tree_node_t * tree_insert(tree_node_t *oldTreep, tree_element_t ele)
{
if(oldTreep == NULL){
oldTreep = TYPED_ALLOC(tree_node_t);
strcpy(oldTreep->element.name, ele.name);
strcpy(oldTreep->element.sName, ele.sName);
oldTreep->element.seatClass = ele.seatClass;
oldTreep->leftp = NULL;
oldTreep->rightp = NULL;
}
else if (strcmp(oldTreep->element.name, ele.name)==0){
/* duplicate key - no insertion */
}
else if (strcmp(oldTreep->element.name, ele.name)>0){
oldTreep->rightp = tree_insert(oldTreep->rightp, ele);
}
else
{
oldTreep->leftp = tree_insert(oldTreep->leftp, ele);
}
return(oldTreep);
}
我的 scan_passenger 功能(我从这个函数调用的结果中传递 ele);
void scan_passenger(tree_element_t *pass)
{
char passName[10], passSname[10];
int classNum;
printf("\nEnter the Name of passenger to add the binary search tree> ");
scanf("%s", passName);
printf("Enter the Surname of passenger to add the binary search tree> ");
scanf("%s", passSname);
printf("Enter the class number of passenger to add the binary search tree> ");
scanf("%d", &classNum);
strcpy(pass->name, passName);
strcpy(pass->sName, passSname);
pass->seatClass = classNum;
}
如果需要,还有我的 typdefs 和 headers;
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define TYPED_ALLOC(type) (type *)malloc(sizeof (type))
typedef struct tree_element_s {
char name[10];
char sName[10];
int seatClass;
}tree_element_t;
typedef struct tree_node_s {
tree_element_t element;
struct tree_node_s *leftp, *rightp;
}tree_node_t;
我的问题是它不会创建二叉搜索树的根。当我尝试向堆中添加一个新元素时,它似乎创建了一个新节点。当我跟踪我的代码时,似乎这个函数的每个实例都返回 NULL。我想说每次当我调用 tree_insert 时,它首先是 if 语句(认为 root 是 NULL)......对不起我的英语不好。而且我在谈论编码术语时可能会犯一些错误(可能是因为我在缺席一年后从那本书中回到了学习C。所以我可能会将它们混合在一起)提前谢谢。