将节点添加到二叉搜索树

时间:2012-11-29 20:16:05

标签: c nodes binary-search-tree

免责声明:这是一项作业。我不是要求明确的代码答案,只是帮助理解我的代码无效的原因。

我正在尝试实现一个基本的二进制搜索树,但我的_addNode(...)函数出现问题。

这是问题所在。当我使用调试器遍历我的代码时,我注意到叶节点在两侧(左侧和右侧)无限创建,因此除了创建根之外,叶节点NULL时从来没有任何意义。 。问题是我要求我的程序在找到一个叶子所在的NULL值时创建一个新节点。因此,如果从未有任何NULL值,则永远不会创建任何新叶,对吧?

我遇到的另一个问题是我的compare(...)功能。在调试器中单步执行它会显示它多次遍历函数,从不实际返回值。当它返回到调用函数时,它会回退到compare(...)函数并无限循环。考虑到我在每个if语句中都有有效的return语句,我不知道为什么会发生这种情况。

以下是您可能需要的所有代码。如果我遗漏了一些东西,请告诉我,我会发布它。

struct Node {
    TYPE         val;
    struct Node *left;
    struct Node *right;
};

struct BSTree {
    struct Node *root;
    int          cnt;
};

struct data {
    int number;
    char *name;
};

int compare(TYPE left, TYPE right)
{
    assert(left != 0);
    assert(right != 0);

    struct data *leftData = (struct data *) left;
    struct data *rightData = (struct data *) right;

    if (leftData->number < rightData->number) {
        return -1;
    }
    if (leftData->number > rightData->number) {
        return 1;
    } else return 0;
}

void addBSTree(struct BSTree *tree, TYPE val)
{
    tree->root = _addNode(tree->root, val);
    tree->cnt++;
}

struct Node *_addNode(struct Node *cur, TYPE val)
{
    assert(val != 0);

    if(cur == NULL) {
        struct Node * newNode = malloc(sizeof(struct Node));
        newNode->val = val;
        return newNode;
    }
    if (compare(val, cur->val) == -1) {
        //(val < cur->val)
        cur->left = _addNode(cur->left, val);
    } else cur->right = _addNode(cur->right, val);

    return cur;
}

编辑:添加以下功能

int main(int argc, char *argv[])
{
    struct BSTree *tree = newBSTree();

    /*Create value of the type of data that you want to store*/
    struct data myData1;
    struct data myData2;
    struct data myData3;
    struct data myData4;

    myData1.number = 5;
    myData1.name = "rooty";
    myData2.number = 1;
    myData2.name = "lefty";
    myData3.number = 10;
    myData3.name = "righty";
    myData4.number = 3;
    myData4.name = "righty";

    /*add the values to BST*/
    addBSTree(tree, &myData1);
    addBSTree(tree, &myData2);
    addBSTree(tree, &myData3);
    addBSTree(tree, &myData4);

    /*Print the entire tree*/
    printTree(tree);
    /*(( 1 ( 3 ) ) 5 ( 10 ))*/
    return 1;
}

2 个答案:

答案 0 :(得分:4)

也许您可以尝试在NULL之后向右和向左设置malloc

struct Node * newNode = malloc(sizeof(struct Node));
newNode->left = NULL;
newNode->right = NULL;

答案 1 :(得分:1)

在此处检查此行(或相应的左侧):

cur-&gt; right = _addNode(cur-&gt; right,val);

如果cur->; right == 0,那很好。但是如果cur-> right!= 0,那么坐在那里的节点将被_addNode的返回值替换,该返回值最终不是整个分支,而只是一个节点。

我喜欢在使用memset(newNode,0,sizeof(struct Node))的malloc之后显式地删除结构中的值。其他人可能不同意。

相关问题