【问题标题】:Binary Search Tree insertion doesn't work二叉搜索树插入不起作用
【发布时间】:2012-08-21 01:50:16
【问题描述】:

我正在关注一本书,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;
}

如果需要,还有我的 typdef 和标题;

#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。所以我可能会混合它们) 提前致谢。

【问题讨论】:

    标签: c binary-tree insertion


    【解决方案1】:

    在 add_to_t 中,你更新了 oldTreep,但由于它是一个局部变量,所以你一离开函数,新值就会丢失。

    例如,您可以将 oldTreep 的新值返回给调用者,调用者会使用返回值更新 他的 oldTreep

    tree_node_t
    add_to_t(tree_node_t *oldTreep, // input/output - binary search tree 
            tree_element_t ele)       // input - element to add 
    { 
        return tree_insert(oldTreep, ele); 
    } 
    
    ...
    
    myRootOfTheTree = add_to_t (myRootOfTheTree, element);
    

    另一种解决方案是在树中始终有一个虚拟元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      相关资源
      最近更新 更多